SELECT *
FROM users_groups
GROUP BY user_id
WHERE group_id IN (2,3)
HAVING COUNT(1) = 2
这当然假设 { user_id
, group_id
} 是唯一的(并且没有其他列可以将其他行添加到计数中)。否则,您可以明确地确保这一点:
SELECT *
FROM users_groups
GROUP BY user_id
WHERE group_id IN (2,3)
HAVING COUNT(DISTINCT group_id) = 2
只有在这两组中稍微复杂一些。你可以这样做:
SELECT *
FROM users_groups g1
GROUP BY user_id
WHERE group_id IN (2,3)
AND NOT EXISTS
(
SELECT 1
FROM users_groups AS g2
WHERE g2.user_id = g1.user_id
AND group_id NOT IN (2,3)
)
HAVING COUNT(1) = 2
或者,
SELECT *
FROM users_groups g1
GROUP BY user_id
HAVING COUNT(1) = 2
AND SUM(CASE WHEN group_id IN (2,3) THEN 1 ELSE 0 END) = 2
在第 2 组和第 3 组中,总共超过 2 组:
SELECT *
FROM users_groups g1
GROUP BY user_id
HAVING SUM(CASE WHEN group_id IN (2,3) THEN 1 ELSE 0 END) = 2
AND COUNT(1) > 2