sql - 具有联合和限制的 knex 子查询

标签 sql postgresql knex.js

我正在尝试执行以下查询:

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/

相关文章:

mysql - Mysql 上的 Gtfs 数据库 - 在区域内搜索路线时查询速度慢

sql - 空日期表现

javascript - 使用 knex.transactionProvider() 时出现 KnexTimeoutError

php - 在一个查询中将值插入多行

mysql - knex 迁移失败,但不会恢复更改

javascript - Knex 迁移导致 gulp 进程挂起

mysql - 如何将数据库中的表转换为文本文件?

mysql - SQL 查询 : How many worst cells do I need to exclude to achieve 90% success rate

postgresql - Clojure JDBC - 此结果集已关闭

mysql - Postgres,创建两列之间值的唯一性