【问题标题】:How to fix the query built by union in knex如何修复 knex 中由 union 构建的查询
【发布时间】:2019-08-03 09:44:18
【问题描述】:

我正在使用带有 pg 的 knex 从我的数据库中获取一些数据。 我试图通过 knex 构建的查询是:

select "fixtime" from "positions" order by "fixtime" desc limit(1) 
union 
select "fixtime" from "positions" order by "fixtime" limit (1)

但是,当我使用“union”时,knex 返回以下查询。当我试图得到结果时,我得到了错误。

console.log(db.select('fixtime').from('positions').orderBy('fixtime').limit(1).union([db.select('fixtime').from('positions').orderBy('fixtime','desc').limit(1)]).toSQL())

这是控制台的结果:

select "fixtime" from "positions" 
union 
select "fixtime" from "positions" order by "fixtime" desc limit ? order by "fixtime" asc limit ?

db.select('fixtime').from('positions').orderBy('fixtime').limit(1).union([db.select('fixtime').from('positions').orderBy('fixtime','desc').limit(1)]).then(arr => console.log)

这是我得到的错误: 未处理的拒绝错误:“订单”处或附近的语法错误

当我使用单个查询时,我可以获得结果。 如何使用 knex 修复此查询或者它是一个错误?

【问题讨论】:

    标签: node.js knex.js pg


    【解决方案1】:

    我相信 Knex 在您尝试这样做的方式中是不可能的。有一个 issue 描述了类似的东西。

    但是...您可以通过使用两个CTEs 来欺骗Postgres 来获得结果

    const sql = db
      .with('first', qb => {
        qb.select('fixtime')
          .from('tc_positions')
          .orderBy('fixtime', 'asc')
          .limit(1);
      })
      .with('last', qb => {
        qb.select('fixtime')
          .from('tc_positions')
          .orderBy('fixtime', 'desc')
          .limit(1);
      })
      .select('*')
      .from('first')
      .union(function() {
        this.select('*').from('last');
      })
      .toSQL();
    
    console.log(sql);
    

    这会产生:

    WITH "first" AS (
        SELECT
            "fixtime"
        FROM
            "tc_positions"
        ORDER BY
            "fixtime" ASC
        LIMIT ?
    ),
    "last" AS (
        SELECT
            "fixtime"
        FROM
            "tc_positions"
        ORDER BY
            "fixtime" DESC
        LIMIT ?
    )
    SELECT
        *
    FROM
        "first"
    UNION
    SELECT
        *
    FROM
        "last"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      • 2015-06-05
      • 2013-10-03
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      • 2019-04-13
      相关资源
      最近更新 更多