knex.js 中的子查询或 knex.js 中的直接 postgresql 查询使用原始或任何替代方式

Subquery in knex.js or direct postgresql queries in knex.js using raw or any alternative ways

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


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'

无需为您转换整个内容,以下是子查询在 Knex 中的工作方式。

每个查询 returns 一个 Knex 查询生成器的实例,我们将其命名为 .as。所以逐步建立它们非常容易:

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