如何在 Sequelize 中加入两个查询
How to Join two Queries in Sequelize
我尝试连接两个查询并根据它找到结果。我可以在 SQL 中编写代码。我的 SQL 密码是
SELECT a.awbid,
m.mpscount
FROM ( select a.awbid
FROM awbmaster a
where a.batchid ='B/117/15022022'
and a.hubid ='117'
) as a
left join ( select count('mpsid') as "mpscount" ,
awbid from
mpsmaster m
where m.batchid = 'B/117/15022022'
group by "awbid"
) as m on a.awbid = m.awbid
但是,我还没有找到任何关于续集的解决方案。我如何在sequelize中编写上面的SQL代码?
首先,我们可以简化此 SQL 查询,只需使用子查询即可找出 mpscount
:
SELECT a.awbid,
(SELECT count(*)
FROM mpsmaster m
WHERE m.batchid = 'B/117/15022022'
AND m.awbid=a.awbid ) AS mpscount
FROM awbmaster a
WHERE a.batchid ='B/117/15022022'
AND a.hubid ='117'
现在如果我们已经有了两个模型 MpsMaster
和 AwbMaster
并且它们之间有正确的关联,那么我们可以发出这样的请求:
const records = AwbMaster.findAll(}
attributes: [
'awbid',
[Sequelize.literal('(SELECT count(*) FROM mpsmaster m WHERE m.batchid = \'B/117/15022022\' AND m.awbid=AwbMaster.awbid)'), 'mpscount']
]
})
我尝试连接两个查询并根据它找到结果。我可以在 SQL 中编写代码。我的 SQL 密码是
SELECT a.awbid,
m.mpscount
FROM ( select a.awbid
FROM awbmaster a
where a.batchid ='B/117/15022022'
and a.hubid ='117'
) as a
left join ( select count('mpsid') as "mpscount" ,
awbid from
mpsmaster m
where m.batchid = 'B/117/15022022'
group by "awbid"
) as m on a.awbid = m.awbid
但是,我还没有找到任何关于续集的解决方案。我如何在sequelize中编写上面的SQL代码?
首先,我们可以简化此 SQL 查询,只需使用子查询即可找出 mpscount
:
SELECT a.awbid,
(SELECT count(*)
FROM mpsmaster m
WHERE m.batchid = 'B/117/15022022'
AND m.awbid=a.awbid ) AS mpscount
FROM awbmaster a
WHERE a.batchid ='B/117/15022022'
AND a.hubid ='117'
现在如果我们已经有了两个模型 MpsMaster
和 AwbMaster
并且它们之间有正确的关联,那么我们可以发出这样的请求:
const records = AwbMaster.findAll(}
attributes: [
'awbid',
[Sequelize.literal('(SELECT count(*) FROM mpsmaster m WHERE m.batchid = \'B/117/15022022\' AND m.awbid=AwbMaster.awbid)'), 'mpscount']
]
})