[英]How to fix the query built by union in knex
I am using knex with pg for getting some data from my DB. 我正在使用pg的knex从数据库中获取一些数据。 The query that I am trying to build by knex is:
我尝试通过knex构建的查询是:
select "fixtime" from "positions" order by "fixtime" desc limit(1)
union
select "fixtime" from "positions" order by "fixtime" limit (1)
but, knex return the following query when I used 'union'. 但是,当我使用“联合”时,knex返回以下查询。 And I get the error when I am trying to get the result.
当我尝试获得结果时出现错误。
console.log(db.select('fixtime').from('positions').orderBy('fixtime').limit(1).union([db.select('fixtime').from('positions').orderBy('fixtime','desc').limit(1)]).toSQL())
this is the result of console: 这是控制台的结果:
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)
this is the error I got: Unhandled rejection error: syntax error at or near "order" 这是我得到的错误:未处理的拒绝错误:“ order”或附近的语法错误
When I used a single query I can get the result. 当我使用单个查询时,可以获得结果。 How can I fix this query with knex or is it a bug?
如何使用knex修复此查询或它是一个错误?
I believe this is not possible with Knex
in the way you are trying it to do. 我相信使用
Knex
不可能做到这一点。 There is an issue that describes something similar. 存在一个描述类似问题的问题 。
But... You can cheat your way to the result with Postgres
by using two CTEs 但是...您可以通过使用两个CTE来利用
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);
this yields: 这产生:
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.