2017-07-07 96 views
0

我有一个大的query从多个表中选择多个列,我想知道有多少记录(做一个计数)。如何计算在Knex中传递子查询的结果?

我无法得到结果的长度,因为我还将.offset.limit添加到查询中。

有没有一种方法,我可以生成以下

SELECT COUNT(*) FROM (
    knex query 
) as count 

与knex?怎么样?

(版本:0.11.10

回答

1

您必须寻找来自users`这个

const knex = require('knex')({ client: 'pg' }) 

const builder = knex 
    .count('t.* as count') 
    // You actually can use string|function with this = knex builder|another knex builder 
    .from(function() { 
     // Your actual query goes here 
     this 
      .select('*') 
      .from('users') 
      .whereNull('some_condition', 'some_value') 
      .as('t') // Alias for your DB (For example Postgres requires that inner query must have an alias) 
    }) 
    .first() 

console.log(builder.toString()) // Prints your query 
// => select count("t".*) from (select * from "users" where "removed_at" is null) as "t" limit 1 
+0

如果您喜欢使用箭头函数,而不是引用此,构建器也作为参数传递给回调函数。像'.from(builder => builder.from('users')。as('t'))' –

0

从当前网站上的文档得到这个。

knex('users').count('active as a') 
Outputs: 
select count(`active`) as `a` from `users` 

Knex documentation v 0.13.0

搜索 “SELECT COUNT” 会给你更多的例子。

+0

这会产生'SELECT COUNT(*),但我需要的是'SELECT COUNT(*)FROM(SELECT * FROM用户)' – BrunoLM

相关问题