mysql - 如何在 rust ,柴油中使用sql函数CAST?

标签 mysql rust 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查询错误:

"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \') = CAST('rainfall'.'datetime')\' at line 1"



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

我的问题是,如何将'as date'组件添加到我的柴油查询中? sql_function定义中缺少什么吗?

谢谢你的帮助。

最佳答案

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

原来,您可以在添加后将原始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)?;

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

关于mysql - 如何在 rust ,柴油中使用sql函数CAST?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59780799/

相关文章:

sql - 如何使用Diesel执行 `UPDATE FROM`?

rust - 具有定制包装类型的柴油机

php - 数据库表中的正则表达式搜索和替换

while-loop - 是否可以在 `while let` 中使用模式匹配守卫?

sql - 使用 derive Insertable for float

rust - 如何改善 Vec 初始化时间?

windows - 如何在Windows中清除控制台

php - 如何用mysql更新设置的记录数?

mysql - 使用 mysql 数据库

php - 根据优先级随机获取记录