【问题标题】:Subquery in knex.js or direct postgresql queries in knex.js using raw or any alternative waysknex.js 中的子查询或 knex.js 中使用原始或任何替代方式的直接 postgresql 查询
【发布时间】:2019-06-02 05:07:22
【问题描述】:

我目前在 express.js 项目中工作,并使用 knex 进行数据库迁移和查询。我在编写查询以获得我在 postgresql (dbeaver) 中得到的确切结果时遇到了麻烦。下面给出了我需要转换为 knex 查询的查询(从表中)。实际上想要根据列的不同值(应用程序)获取列的计数


select count(job_id) as total_applicants ,

(select count(job_id) from applications as APPL join 
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='qualified' and POS.creator_id='e5f604be-e773-490b- 
a525-fad3b95fd941') as qlCount,
(select count(job_id) from applications as APPL join 
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='backup' and POS.creator_id='e5f604be-e773-490b-a525- 
fad3b95fd941') as bckCount,
(select count(job_id) from applications as APPL join 
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='interview' and POS.creator_id='e5f604be-e773-490b- 
a525-fad3b95fd941') as intrCount,
(select count(job_id) from applications as APPL join 
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='offer' and POS.creator_id='e5f604be-e773-490b-a525- 
fad3b95fd941') as offrCount,
(select count(job_id) from applications as APPL join 
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='screening' and POS.creator_id='e5f604be-e773-490b- 
a525-fad3b95fd941') as screenCount,
(select count(job_id) from applications as APPL join 
recruiter_positions as POS on POS.position_id=APPL.job_id
where APPL.state='rejected' and POS.creator_id='e5f604be-e773-490b- 
a525-fad3b95fd941') as rejectedCount

from applications as APPL join recruiter_positions as POS on 
POS.position_id=APPL.job_id
where APPL.state notnull and POS.creator_id='e5f604be-e773-490b-a525- 
fad3b95fd941'

【问题讨论】:

  • 欢迎来到 SO。由于您是新手,请查看How to Askminimal reproducible example 部分。很抱歉,您的帖子中没有提供任何有用的信息,甚至没有提供任何实际问题。
  • 我放在这里的查询在 postgresql 中按预期工作,只是想将其转换为 knex。实际上想根据列的不同值获取列的计数

标签: node.js database postgresql knex.js


【解决方案1】:

在不为您转换整个内容的情况下,下面是子查询在 Knex 中的工作方式。

每个查询都返回一个 Knex 查询构建器的实例,我们将其别名为 .as。所以逐步建立它们很容易:

const subquery1 = knex("foos").count("*").as("foocount");
const subquery2 = knex("bars").count("*").as("barcount");
knex.select(subquery1, subquery2).then(console.log);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    相关资源
    最近更新 更多