Knex中的子查询

时间:2014-03-26 22:03:35

标签: knex.js

我希望在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: 

2 个答案:

答案 0 :(得分:25)

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()

答案 1 :(得分:3)

编辑:此答案涉及旧版本的knex。请参阅other answer

当我这样做时,我使用knex.raw功能。您可以在其中放置任何原始SQL。像这样:

 var selectRaw = "SUM( IF( "+ table.id +" = 1, "+ table.value +", 0.00 )) as customAlias";
 query.column( knex.raw( selectRaw ) );

您甚至可以使用knex构建查询,然后使用.toString()方法填充knex.raw。我的示例不是他们的API的一部分(那些IF s ...)。