mysql - 如何在 rust、diesel 中使用 sql 函数 CAST?
问题描述
我正在使用 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 服务器版本相对应的手册,以在第 1 行的 \') = CAST('rainfall'.'datetime')\' 附近使用正确的语法”
如原始 SQL 语句所示,它应为CAST('rainfall'.'datetime' 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)?;
我希望这对其他人有帮助!
推荐阅读
- opencv - 如何在使用 OpenCV 设置破坏网络摄像头后将其恢复为默认设置?
- html - 具有 set Input() 任何类型的可重用组件是一个好习惯吗?
- winforms - 使用 EF Code First 创建数据库时指定数据库路径
- linux - cPanel 安装问题
- vue.js - 禁用规则时,vue-cli linting 抛出驼峰警告
- visual-c++ - 如何“正确关闭 MFC 无模式对话框并修复资源泄漏”
- java - 授权不起作用(Spring Security)
- node.js - 如何使用 node.js 和 react.js 下载大型 CSV 文件
- java - notifyItemInsertedRange() 不适用于 recyclerview 适配器
- android - 使用 React Native 和 Expo 实现闹钟(iOS 和 Android)