如何计算在 Knex 中通过子查询的结果?
How to count results passing a subquery in Knex?
我有一个大query
,从多个表中选择多个列,我想知道有多少条记录(正在统计)。
我无法获取结果的长度,因为我还在查询中添加了 .offset
和 .limit
。
有什么方法可以生成以下内容
SELECT COUNT(*) FROM (
knex query
) as count
带膝盖?怎么样?
(版本:0.11.10
)
从当前站点的文档中获取。
knex('users').count('active as a')
Outputs:
select count(`active`) as `a` from `users`
搜索 "select count" 将为您提供更多示例。
你一定在找这个
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
下面的代码returns给定复杂内部查询的计数:
async getTotalCount() {
const clonedKnexObject = knexObject.clone();
clonedKnexObject.limit(999999);
const countQuery = knex.from(clonedKnexObject.as('a')).count();
const response = await dbQuery(countQuery.toSQL().toNative());
return response[0]['count(*)'];
}
注意:我需要设置 .limit(999999),因为我需要覆盖的现有限制要低得多。
我有一个大query
,从多个表中选择多个列,我想知道有多少条记录(正在统计)。
我无法获取结果的长度,因为我还在查询中添加了 .offset
和 .limit
。
有什么方法可以生成以下内容
SELECT COUNT(*) FROM (
knex query
) as count
带膝盖?怎么样?
(版本:0.11.10
)
从当前站点的文档中获取。
knex('users').count('active as a')
Outputs:
select count(`active`) as `a` from `users`
搜索 "select count" 将为您提供更多示例。
你一定在找这个
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
下面的代码returns给定复杂内部查询的计数:
async getTotalCount() {
const clonedKnexObject = knexObject.clone();
clonedKnexObject.limit(999999);
const countQuery = knex.from(clonedKnexObject.as('a')).count();
const response = await dbQuery(countQuery.toSQL().toNative());
return response[0]['count(*)'];
}
注意:我需要设置 .limit(999999),因为我需要覆盖的现有限制要低得多。