gpt4 book ai didi

rust - 如何在柴油中实现嵌套过滤器?

转载 作者:行者123 更新时间:2023-12-03 11:45:35 27 4
gpt4 key购买 nike

我对 Rust 和 Diesel 还很陌生。我现在正在尝试为这样的查询实现 Diesel 过滤:

-- @param1 is duration in years
-- @param2 is duration in months

SELECT columns FROM a
WHERE
(...dynamic AND clauses)
AND (((a.min_unit = "Years") AND (a.min_duration <= @param1))
OR ((a.min_unit = "Months") AND (a.min_duration <= @param2)))
(...dynamic AND clauses)

在文档和网络上进行一些搜索后,我仍然找不到如何执行此操作。我最接近的猜测是:

let param1 = ...;
let param2 = ...;

let mut query = a::table.select(a::all_columns).into_boxed();
// dynamic clauses: query = query.filter(...) ...
query = query.filter(a::min_unit.eq(Some("Years")).and(a::min_duration.le(Some(param1))))
.or_filter(a::min_unit.eq(Some("Months")).and(a::min_duration.le(Some(param2))));
// dynamic clauses: query = query.filter(...) ...

let results = a::table.load<A>(&*conn);

有人有想法吗?

谢谢!

最佳答案

嗯,这是我最近的尝试:

let min_months_predicate = a::min_unit.eq(Some("Months"))
.and(a::min_duration.le(Some(param1)));
let min_years_predicate = a::min_unit.eq(Some("Years"))
.and(a::min_duration.le(Some(param1)));

query = query.filter(min_months_predicate.or(min_years_predicate))
.filter(a::max_duration.ge(Some(param2)));

debug!("TEST QUERY: {:?}", debug_query(&query));

产生这个查询:

"SELECT \"a\".\"id\", \"a\".\"code\", .... WHERE (\"a\".\"min_unit\" = $1 AND \"a\".\"min_duration\" <= $2 OR \"a\".\"min_unit\" = $3 AND \"a\".\"min_duration\" <= $4) AND \"a\".\"max_duration\" >= $5"

当我在这个查询中使用 sql EXPLAIN 时,我得到了这个子句:

  Filter: ((max_duration >= 60) AND (((min_unit = 'Months'::text) AND (min_duration <= 3)) OR ((min_unit = 'Years'::text) AND (min_duration <= 5))))

这似乎是正确的。

关于rust - 如何在柴油中实现嵌套过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61769508/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com