我正在尝试执行以下查询:
select *
from A
where id in (
(select id from A where created_at >= '2018-12-25' order by created_at asc limit 1)
union
(select id from A where created_at < '2018-12-26' order by created_at desc limit 1)
)
我对 knex 的尝试是:
knex.select('*')
.from('A')
.whereIn('id', qb =>
qb.select('*')
.from('A')
.where('created_at', '>=', '2018-12-25')
.orderBy('created_at', 'ASC')
.limit(1)
.union(qb =>
qb.select('*')
.from('A')
.where('created_at', '<', '2018-12-26')
.orderBy('created_at', 'DESC')
.limit(1)
)
)
但它会产生不同的 SQL:
select *
from "A"
where "id" in (select * from "A" where "created_at" >= ? union select * from "A" where "created_at" < ? order by "created_at" DESC limit ? order by "created_at" ASC limit ?)
似乎 order by
子句没有按照我想要的方式处理,而且括号组也不一样。我的错误是什么?我该如何正确使用 knex?
最佳答案
以下将输出您想要的 sql,但我想这不是做事的有效方法。
const sql = knex.select('*')
.from('A')
.whereIn('id', qb =>
qb.union(qb =>
qb.select('*')
.from('A')
.where('created_at', '>=', '2018-12-25')
.orderBy('created_at', 'ASC')
.limit(1)
)
.union(qb =>
qb.select('*')
.from('A')
.where('created_at', '<', '2018-12-26')
.orderBy('created_at', 'DESC')
.limit(1)
, false)
)
.toSQL();
console.log(sql) ;
关于sql - 具有联合和限制的 knex 子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53941928/