gpt4 book ai didi

knex.js - Knex 中的子查询

转载 作者:行者123 更新时间:2023-12-04 00:06:36 29 4
gpt4 key购买 nike

我希望基本上在 Knex 中进行此类查询,但我无法使其正常工作:

select distinct *
from
(
select *, 1 as rank from table1 where Word like 'mike'
union
select *, 2 as rank from table1 where Word like 'mike%'
union
select *, 3 as rank from table1 where Word like '%mike%'
) as X
order by WordOrder

我注意到一个类似的问题 here并试图遵循他们的建议,但似乎无法发现我的错误(或者这是否是首先这样做的正确方法)。

var q = DB.knex('Users').select("*", "1 as rank").where("User", "like", query).
union(function() {
this.select("*", "2 as rank").where("User", "like", query + "%")
}).
union(function() {
this.select("*", "3 as rank").where("User", "like", query + "%")
});

DB.knex("Users").distinct("*").from('(' + q.toString() + ') as X').
orderBy('rank').select().then(...)

如果有任何帮助,该特定查询会生成以下错误:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1`` order by `rank` asc' at line 1, sql: select distinct * from `select` as ``1`` order by `rank` asc, bindings: 

最佳答案

knex 0.6 版现在几乎可以让您在任何地方使用子查询。在 http://knexjs.org 的 chrome 控制台中弹出这个你应该看到它给了你你想要的东西

knex.distinct('*').from(function() {
this.union(function() {
this.select('*', '1 as rank').from('table1').where('Word', 'like', 'mike')
}).union(function() {
this.select('*', '2 as rank').from('table1').where('Word', 'like', 'mike%')
}).union(function() {
this.select('*', '3 as rank').from('table1').where('Word', 'like', '%mike%')
})
.as('X')
}).orderBy('WordOrder').toString()

关于knex.js - Knex 中的子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22674003/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com