简体   繁体   English

Knex.js中的查询换行

[英]Query wrap in Knex.js

How do we wrap queries into groups on union? 我们如何将查询打包到联合的组中?

I have this query: 我有这个查询:

    SELECT * FROM (
       (SELECT u1.* FROM `user` AS u1 WHERE user_email IS NOT NULL GROUP BY u1.key)
       UNION ALL
       (SELECT u2.* FROM `user` AS u2 WHERE user_email IS NULL)
) AS u ORDER BY u.id LIMIT 10

I was only able to do up to this: 我只能做到这一点:

knex.select('*').from('user').whereNotNull('email').groupBy('user.key')
.unionAll(function() {
  this.select('*').from('user as u2').whereNull('u2.email');
}, true)

But this would result to: 但这将导致:

SELECT user.* FROM `user` WHERE user.email IS NOT NULL
UNION ALL
(SELECT u2.* FROM `user` AS u2 WHERE email IS NULL)
GROUP BY user.key

which is a fail. 这是一个失败。 Is there a way to do this? 有没有办法做到这一点? I need something like the first query because I need to retrieve sorted by id and paginated. 我需要类似第一个查询的内容,因为我需要检索按ID排序并分页的内容。

How unionAll works in knex is quite problematic when combined with groupBy etc. 当与groupBy等结合使用时,unionAll在unionAll工作方式存在很大问题。

So I would go with knex.raw which is pretty powerful for any kind of complex query combining. 因此,我将使用knex.raw ,它对于任何类型的复杂查询组合都非常强大。 Nice thing with knex raw is that you can use normal query builders for most of the parts and just write needed parts of the query as raw. 使用knex raw的好处是,您可以对大多数部分使用常规查询构建器,而只需将查询的所需部分写为原始。

https://runkit.com/embed/905uidg7qdiw https://runkit.com/embed/905uidg7qdiw

Anyways this is one way to do it: 无论如何,这是一种实现方法:

knex.from(
  knex.raw('? UNION ALL ? AS u', [
    knex('user').select('*').whereNotNull('user_email').groupBy('key'),
    knex('user').select('*').whereNull('user_email')
  ])
).orderBy('u.id').limit(10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM