我正在尝试执行以下查询:
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正确执行操作?
答案 0 :(得分:0)
以下操作将输出您所需的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) ;