繁体   English   中英

如何在 rust、diesel 中使用 sql 函数 CAST?

[英]How can I use the sql function CAST in rust, diesel?

我正在使用 Rocket 开发一个新端点,并试图返回一个由各种结构组成的 Vec<>。

我想在柴油中复制的原始查询是:

select location.id, location.name, w.datetime, t.temp, w.compass, w.speed, r.probability, s.height
from location
inner join rainfall r on location.id = r.location
inner join temperature t on location.id = t.location
inner join wind w on location.id = w.location
inner join swell s on location.id = s.location
where t.datetime = w.datetime
  and s.datetime = t.datetime
  and CAST(t.datetime as date) = CAST(r.datetime as date)
  and t.datetime > now() and t.datetime < NOW() + INTERVAL 1 HOUR;

我认识到,为了使用 CAST 函数,我需要使用sql_function! 宏:

sql_function! {
#[sql_name="CAST"]
    fn cast(x: sql_types::Nullable<sql_types::Datetime>) -> sql_types::Date;
}

这允许我创建以下查询:

let summaries: Vec<(Location, Swell, Wind, Temperature, Rainfall)> = location::table
        .inner_join(swell::table)
        .inner_join(wind::table)
        .inner_join(temperature::table)
        .inner_join(rainfall::table)
        .filter(temperature::datetime.eq(wind::datetime))
        .filter(temperature::datetime.eq(swell::datetime))
        .filter(temperature::datetime.gt(utilities::today()))
        .filter(temperature::datetime.lt(utilities::future_hour(1)))
        .filter(cast(temperature::datetime).eq(cast(rainfall::datetime)))
        .load(&conn.0)?;

但是,当我运行此查询时,出现 SQL 查询错误:

“您的 SQL 语法有错误;请检查与您的 MySQL 服务器版本相对应的手册,以在 \\') = CAST('rainfall'.'datetime')\\' 第 1 行附近使用正确的语法”

如原始 SQL 语句所示,它应该读取CAST('rainfall'.'datetime' as date)

我的问题是,如何将“作为日期”组件添加到我的柴油查询中? sql_function 定义中是否缺少某些内容?

谢谢你的帮助。

在深入研究类似问题后,我找到了答案。

原来你可以在添加.filter一个原始的 sql 字符串输入到.filter方法中: use diesel::expression::sql_literal::sql; .

所以最后的片段变成:

let summaries: Vec<(Location, Swell, Wind, Temperature, Rainfall)> = location::table
        .inner_join(swell::table)
        .inner_join(wind::table)
        .inner_join(temperature::table)
        .inner_join(rainfall::table)
        .filter(temperature::datetime.eq(wind::datetime))
        .filter(temperature::datetime.eq(swell::datetime))
        .filter(temperature::datetime.gt(utilities::today()))
        .filter(temperature::datetime.lt(utilities::future_hour(1)))
        .filter(sql("CAST(`temperature`.`datetime` as date) = CAST(`rainfall`.`datetime` as date)"))
        .load(&conn.0)?;

我希望这对其他人有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM