node.js - 如何在 knex 中使用嵌套选择查询

标签 node.js knex.js

我想使用 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})


但没有成功

最佳答案

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

关于node.js - 如何在 knex 中使用嵌套选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57495739/

相关文章:

mysql - Bookshelf.js 获取数据透视表属性

javascript - 如何用 Knex.js 查询多对多关系?

mysql - Knex迁移: Transaction query already complete

Node.js express : confuse about router middleware

node.js - 带有调用 TLS 证书 (JKS) 的 NODE JS soap 请求

javascript - Google Chrome 未经授权的响应导致弹出窗口

javascript - 如何使用 Knex.js 在 Mysql 列中使用枚举类型设置默认值?

java - (Node.js、socket.io)JSONObject 无法转换为 int

node.js - 显示来自 GridFS 的 HTML 图像

mysql - 如何用nodejs从mysql解码汉字