您应该加入您的表格并使用 HAVING 关键字过滤结果:
SELECT games.game, COUNT(games.ga_id), ga_eq.eq_id FROM `games`
JOIN ga_eq USING (ga_id)
JOIN equipements USING (eq_id)
GROUP BY games.ga_id
HAVING COUNT(games.ga_id)=1 AND eq_id=1
这是方法:获取所有行
SELECT games.game, ga_eq.eq_id FROM `games`
JOIN ga_eq USING (ga_id) JOIN equipements USING (eq_id)
结果 :
然后 grouby ID 并计算一个数字 ID(所以数字设备)
SELECT games.game, ga_eq.eq_id, COUNT(games.ga_id) FROM `games`
JOIN ga_eq USING (ga_id) JOIN equipements USING (eq_id)
GROUP BY games.ga_id
然后使用 HAVING 关键字只保留一个设备的游戏并将您的 eq_id 过滤器放在 HAVING CLAUSE 中(不在 WHERE 子句中)
SELECT games.game, ga_eq.eq_id, COUNT(games.ga_id)
FROM `games` JOIN ga_eq USING (ga_id) JOIN equipements USING (eq_id)
GROUP BY games.ga_id HAVING COUNT(games.ga_id)=1 AND eq_id=1
结果 :
更改过滤器AND eq_id=3
-> 空结果
对于许多设备 ID,查询有点不同,我尝试制作一个通用但没有发现,如果其他人有想法?
SELECT g.game, equipements.eq_id, (
SELECT COUNT( eq_id ) FROM ga_eq
WHERE ga_id = g.ga_id
AND eq_id IN (1, 2)
) AS nb_eq
FROM `games` g
JOIN ga_eq USING ( ga_id )
JOIN equipements USING ( eq_id )
GROUP BY game
HAVING nb_eq =2
您必须更改AND eq_id IN (1, 2)
ANDHAVING nb_eq =2
才能更改输入