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

Rust Diesel统计PostgreSQL表行数时出现i32不匹配BigInt Trait错误

问题根源

PostgreSQL 原生的 COUNT 聚合函数返回值类型是 BIGINT,对应 Diesel 中为 BigInt SQL类型,Rust侧默认匹配的类型是 i64 而非你代码里用的 i32,所以触发了类型不匹配的 trait 实现报错,和你的业务表字段有没有用大整型没有关系。

解决方案

方案1:直接改用i64接收结果(推荐)

把代码里的接收类型、函数返回值都改成i64即可,这是成本最低的方案,也符合PG的返回类型约定。count查询必然返回有效值,所以可以去掉不必要的Option包装:

fn get_total_accounts(&self, employee_id: &str) -> anyhow::Result<i64> {
        let res: i64 = employee::table
            .inner_join(account::table)
            .filter(employee::dsl::employee_id.eq(employee_id))
            .count()
            .get_result(&self.pool.get()?)?;
        Ok(res)               
 }

如果后续业务需要i32类型,拿到i64结果后手动做类型转换即可。

方案2:显式转换count结果为SQL整型

如果业务上必须直接用i32接收查询结果,可以在查询时显式把count的输出转换为SQL的Integer类型:
首先导入依赖类型:

use diesel::dsl::Integer;

修改查询代码:

fn get_total_accounts(&self, employee_id: &str) -> anyhow::Result<i32> {
        let res: i32 = employee::table
            .inner_join(account::table)
            .filter(employee::dsl::employee_id.eq(employee_id))
            .count()
            .cast::<Integer>()
            .get_result(&self.pool.get()?)?;
        Ok(res)               
 }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:36:01