NodeJS 如何在knex中使用嵌套选择查询

du7egjpx  于 2023-08-04  发布在  Node.js
关注(0)|答案(3)|浏览(120)

我想添加一个子查询作为一个列使用knex。
SQL查询示例:

select
    name, 
    (select count(*) from employee where employee.dept_id = 1) as employees_count
 from 
    department
 where
    department.id = 1

字符串
我试过了

knex('department').select('name', knex('employee').count().where({dept_id: 1}))
.where({id: 1})


但是没有用

dgiusagp

dgiusagp1#

const Knex = require('knex');

const knex = Knex({
  client: 'pg',
});

knex('department').select(
  'name', 
  knex('employee').count().where({dept_id: 1})
    .as('employees_count')
).where({id: 1}).toSQL().sql;

// "select \"name\", (select count(*) from \"employee\" where… \"employees_count\" from \"department\" where \"id\" = ?"

字符串
https://runkit.com/embed/q22w8v6z5n61

ia2d9nvy

ia2d9nvy2#

为了帮助自己定位问题,可以将.debug()添加到querybuilder中。这使您可以查看实际呈现的查询。这不会解决您的问题,但会给予您了解Knex如何看待您的查询。
要解决您的问题,请尝试selectraw的某种组合。喜欢的:

let emp = knex('employee').count().where({ dept_id: 1 })
knex('department')
.select('name')
.select(knex.raw('? as employee_count', emp))
//.debug()

字符串
使用.debug()清除次要问题。

d8tt03nd

d8tt03nd3#

如果您需要将员工“加入”到部门,如

(select count(*) from employee where dept_id = departament.id) as employees_count

字符串
你可以尝试Mikael的解决方案whereRaw

knex('department').select([
  'name', 
  knex('employee')
    .count()
    .whereRaw('employee.dept_id = department.id')
    .as('employees_count'),
]).where({id: 1})

相关问题