【问题标题】:knex subquery with union and limit具有联合和限制的 knex 子查询
【发布时间】:2019-05-25 07:10:41
【问题描述】:

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

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?

【问题讨论】:

  • 联合真的有用吗?
  • @DanielE。好吧,如果您有想法如何重构它以获得相同的结果,那也将不胜感激,但我最初的想法是从 id 列表中选择 *,这是两个子查询的结果,与联合统一,产生 id在给定日期创建的第一个项目和在给定日期创建的最后一个项目的 id。即使我可以在没有工会的情况下做到这一点,我也会很高兴知道我在这里想念什么
  • 您能说明一下建议的用法吗?如果我理解你是正确的,那将输出在间隔内创建的所有行,而我只需要 2 - 第一个和最后一个
  • 我知道sql但不知道knex.js,我的回答可能出问题了
  • 是的,我知道如何在这里用原始 sql 查询我想要的东西,整个问题是关于用 knex 来做这件事

标签: sql postgresql knex.js


【解决方案1】:

以下将输出您想要的 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) ;

【讨论】:

  • 非常感谢!作为更有效的方法,您有什么建议?
  • 这取决于你的数据库结构。
猜你喜欢
  • 2017-02-15
  • 2015-07-08
  • 1970-01-01
  • 2014-05-05
  • 2016-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多