Rust sqlx插件查询mysql报错类型mismatched types

rust sqlx Mysql
作者:dulucy
发布时间:2025-04-27 16:22:25
Rust sqlx插件查询mysql报错类型mismatched types

问题描述

在开发本博客的网站访问量、文章数量和分类数量的统计时,使用了sum(ba.quantity )views进行统计,struct进行数据处理,执行时报错

错误信息:
mismatched types; Rust type `i64` (as SQL type `BIGINT`) is not compatible with SQL type `DECIMAL`
sql语句
select 
COUNT(ba.id) articles,
sum(ba.quantity )views,
(select COUNT(*) from blog_category where blog_category.status  =0)categories
from blog_article ba 
where ba.status =1
结构体
#[derive(Serialize, Deserialize, FromRow)]
pub struct WebCount {
    // 访问量
    pub views: i64,
    // 文章数量
    pub articles: i64,
    // 分类数量
    pub categories: i64,
}
查询方法
pub async fn get_web_count_m(db: &web::Data<AppState>) -> Result<WebCount, Error> {
    let pool = &db.mysql_db;
    let result = sqlx::query_as::<_, WebCount>(
        "select 
            COUNT(ba.id) articles,
           CAST(sum(ba.quantity ) AS SIGNED)  views,
            (select COUNT(*) from blog_category where blog_category.status  =0)categories
            from blog_article ba 
            where ba.status =1") 
    .fetch_one(pool)
    .await;
    match result {
        Ok(res)=>{
            return Ok(res);
        },
        Err(e)=>{
            println!("获取网站统计数据报错:{}", e);
            Err(e.into())
        }
    }
}

原因

经过测试,实际上时views的类型无法匹配导致的。在DBever上查询,显示的是整数,所以就使用 i64的类型,时间上,sum() 函数返回的的DECIMAL。 在MySQL中,SUM函数用于计算数值列的总和。SUM函数的返回类型取决于其参数的类型。 返回类型

  1. 精确值参数(如整数或DECIMAL类型):SUM函数返回DECIMAL类型的值。

  2. 近似值参数(如FLOAT或DOUBLE类型):SUM函数返回DOUBLE类型的值

SELECT SUM(int_column) FROM table_name; -- 返回DECIMAL类型
SELECT SUM(float_column) FROM table_name; -- 返回DOUBLE类型

解决办法

根据自己的需要,对sum() 函数返回值进行类型转换即可。

select 
            COUNT(ba.id) articles,
           CAST(sum(ba.quantity ) AS SIGNED)  views,
            (select COUNT(*) from blog_category where blog_category.status  =0)categories
            from blog_article ba 
            where ba.status =1