假设我有下表,
+---------+------------+
| id | names |
+---------+------------+
| 1 | a |
| 1 | b |
| 1 | c |
| 1 | d |
| 2 | b |
| 3 | a |
| 3 | b |
| 3 | c |
| 4 | c |
+---------+------------+
我想使用具有所有名称“ a”,“ b”和“ c”的SQL查询来获取ID。
答案是1和3。
请修改标题,使其更适合上述问题。
答案 0 :(得分:3)
使用GROUP BY
和HAVING COUNT(DISTINCT names)
,可以获得预期的结果:
SELECT id
FROM TableName
WHERE names IN ('a', 'b', 'c')
GROUP BY id
HAVING COUNT(DISTINCT names) = 3
答案 1 :(得分:2)
您可以使用group by
和having
。假设没有重复:
select id
from t
where names in ('a', 'b', 'c')
group by id
having count(*) = 3;
如果允许重复,请使用:
having count(distinct name) = 3
答案 2 :(得分:0)
我认为这将更好地解决问题
SELECT * from (SELECT id, GROUP_CONCAT( TRIM(names) ORDER BY names SEPARATOR',') agg_name FROM table GROUP BY id)A where A.agg_name = 'a,b,c';