假设我们有联合room_human
/ rooms
的表humans
。需要获得room
仅包含具体内容,某些humans
而非human
。如果您使用human_id IN (1,2,3,4,5)
查询行,则可以获得0-N
行,包括rooms
和其他humans
行。有没有办法选择严格遵守IN
结果的行?要仅获得5行,只有rooms
包含具体的5 humans
(例如IN (1,2,3,4,5)
)?我知道,问题可以通过多种方式解决,但我想要1个查询。我想一个额外的嵌套查询,但是......但突然间我错过了一些最简单的东西?
更新1:我的一个子查询解决方案:
SELECT a.room_id, COUNT(a.id) AS ac, c.bc
FROM room_human a
LEFT JOIN (
SELECT COUNT(b.id) AS bc, b.room_id
FROM room_human b
WHERE b.human_id NOT IN (1, 2, 3, 4, 5)
GROUP BY b.room_id
) AS c ON c.room_id = a.room_id
WHERE a.human_id IN (1, 2, 3, 4, 5)
GROUP BY a.room_id
- 预期结果,例如ac = 5,bc = NULL
更新2:我提出了一个疯狂的解决方案:
SELECT rh.room_id, GROUP_CONCAT(rh.human_id ORDER BY rh.human_id) AS gc
FROM room_human rh
GROUP BY rh.room_id
HAVING gc='1,2,3,4,5';
- 此分组,但不是嵌套查询。但有必要思考。
答案 0 :(得分:1)
一种方法是使用额外的NOT EXISTS
相关子查询:
SELECT *
FROM room_human t
WHERE t.human_id IN (1,2,3,4,5)
AND NOT EXISTS (
SELECT *
FROM room_human o
WHERE o.room_id=t.room_id
AND o.human_id NOT IN (1,2,3,4,5)
)
由于您对拥有单一占用者的房间感兴趣,另一种方法是使用GROUP BY
和HAVING
:
SELECT MIN(human_id), room_id
FROM room_human
WHERE human_id IN (1,2,3,4,5)
GROUP BY room_id
HAVING COUNT(*)=1
答案 1 :(得分:0)
尚未找到的其他解决方案:
SELECT rh.room_id
FROM room_human rh
GROUP BY rh.room_id
HAVING GROUP_CONCAT(rh.human_id ORDER BY rh.human_id)='1,2,3,4,5';