You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust Diesel关联两表基于created_at字段按起止日期筛选查询问题

前置准备

首先修正Diesel Schema定义中的字段命名,避免Rust语法报错:

  • 把employee-id改为employee_id、account-balnce改为account_balance,下划线命名符合Rust及Diesel的开发规范
  • 确保accounts表的created_at字段类型定义为diesel::sql_types::Date,和Postgres的日期类型对应

关联关系定义

在模型代码中添加两张表的关联配置:

use crate::schema::accounts;
// Account表模型定义
#[derive(Queryable, Debug, Associations)]
#[belongs_to(Employee)]
#[table_name = "accounts"]
pub struct Account {
    pub account: i32,
    pub employee_id: i32,
    pub account_balance: i32,
    pub created_at: chrono::NaiveDate,
}

// Employee表模型定义
#[derive(Queryable, Debug, Identifiable)]
#[table_name = "employees"]
pub struct Employee {
    pub id: i32,
    pub employee_name: String,
    pub employee_email: String,
}

筛选查询代码

用内连接关联两张表,同时匹配传入的user_id和日期范围条件即可完成需求:

use diesel::prelude::*;
use chrono::NaiveDate;
use crate::schema::{employees, accounts};

// 参数说明:
// conn:  Postgres数据库连接实例
// input_user_id: 传入的待筛选用户ID
// start_date: 筛选起始日期,构造示例:NaiveDate::from_ymd(2021,9,1)
// end_date: 筛选结束日期
pub fn query_employee_accounts(
    conn: &PgConnection,
    input_user_id: i32,
    start_date: NaiveDate,
    end_date: NaiveDate
) -> QueryResult<Vec<(Employee, Account)>> {
    employees::table
        .inner_join(accounts::table)
        .filter(employees::id.eq(input_user_id))
        .filter(accounts::created_at.between(start_date, end_date))
        .load::<(Employee, Account)>(conn)
}

如果不需要返回两张表的全量字段,把load方法的泛型改为自定义的返回结构体即可。

注意:如果你的created_at存储的是带时区的时间戳,把字段类型换成chrono::DateTime<chrono::Utc>,Schema里对应diesel::sql_types::Timestamptz即可,筛选逻辑不需要调整。

内容的提问来源于stack exchange,提问作者nagaraj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:06:05