我正在mysql中运行以下查询。
SELECT jobtype_has_trade.jobtype_id,users_jobtype.user_id
FROM users
LEFT JOIN subcontractor ON users.subcontractor_id = subcontractor.id
AND subcontractor.quotations = "YES"
LEFT JOIN users_jobtype ON users.id = users_jobtype.user_id
AND users_jobtype.status = "A"
LEFT JOIN jobtype_has_trade ON users_jobtype.jobtype_trade_id = jobtype_has_trade.id
WHERE users.is_subcontractor = "YES"
AND users.has_android = "YES"
AND jobtype_has_trade.jobtype_id IN (1,3,4)
ORDER by users_jobtype.user_id ASC
我正在得到这个输出
在上面的记录中,我只需要具有jobtype_id 1,3和4的user_id。因此,user_id 3和7是可以接受的,而9则不是,因为它只有3和4作为jobtype_id ...在上面的查询中,只有3和7作为user_id?
答案 0 :(得分:1)
一种选择是将having clause
与group by
一起使用
SELECT users_jobtype.user_id
FROM users
LEFT JOIN subcontractor ON users.subcontractor_id = subcontractor.id
AND subcontractor.quotations = "YES"
LEFT JOIN users_jobtype ON users.id = users_jobtype.user_id
AND users_jobtype.status = "A"
LEFT JOIN jobtype_has_trade ON users_jobtype.jobtype_trade_id = jobtype_has_trade.id
WHERE users.is_subcontractor = "YES"
AND users.has_android = "YES"
AND jobtype_has_trade.jobtype_id IN (1,3,4)
group by users_jobtype.user_id
having count(distinct jobtype_has_trade.jobtype_id)=3
答案 1 :(得分:1)
只需检查每个用户在1,3,4中是否存在jobtype_id。我不知道你的架构 如果您在users_jobtype中有jobtype_id,则无需在子查询中的何处(在我的解决方案中)加入
的jobtype_has_tradeSELECT jobtype_has_trade.jobtype_id,
users_jobtype.user_id
FROM users
LEFT JOIN subcontractor ON users.subcontractor_id = subcontractor.id
AND subcontractor.quotations = "YES"
LEFT JOIN users_jobtype ON users.id = users_jobtype.user_id
AND users_jobtype.status = "A"
LEFT JOIN jobtype_has_trade ON users_jobtype.jobtype_trade_id = jobtype_has_trade.id
WHERE users.is_subcontractor = "YES"
AND users.has_android = "YES"
AND jobtype_has_trade.jobtype_id IN (1,
3,
4)
and exists( select jobtype_id from jobtype_has_trade inner join users_jobtype on users_jobtype.jobtype_trade_id=jobtype_has_trade.id where users_jobtype.user_id=users.id and
jobtype_has_trade.jobtype_id=1
)
and exists( select jobtype_id from jobtype_has_trade inner join users_jobtype on users_jobtype.jobtype_trade_id=jobtype_has_trade.id where users_jobtype.user_id=users.id and
jobtype_has_trade.jobtype_id=3
)
and exists( select jobtype_id from jobtype_has_trade inner join users_jobtype on users_jobtype.jobtype_trade_id=jobtype_has_trade.id where users_jobtype.user_id=users.id and
jobtype_has_trade.jobtype_id=4
)
ORDER BY users_jobtype.user_id ASC