我有一个包含两列的数据库表:id
和status
。
status
可以有三个不同的值,A
,B
和C
。
我现在希望获得具有所有三种不同状态(id
,A
和B
)的C
个。
id status
1 A
2 A
1 B
3 A
3 B
3 C
答案 0 :(得分:3)
您可以使用HAVING
:
SELECT id
FROM tab
GROUP BY id
HAVING COUNT(DISTINCT status) = (SELECT COUNT(DISTINCT STATUS) FROM tab);
获得完整的行:
SELECT *
FROM tab
WHERE id IN ( SELECT id
FROM tab
GROUP BY id
HAVING COUNT(DISTINCT status) =
(SELECT COUNT(DISTINCT STATUS) FROM tab)
);
<强> DBFiddle Demo 强>
答案 1 :(得分:1)
我在答案中做了两个假设。你知道吗&#39; A&#39; B&#39; B&#39;和&#39; C&#39;这些状态只会出现一次。也许在(id,status)上有一个UNIQUE约束。
SELECT id FROM tab GROUP BY id HAVING (COUNT(1) == 3);
答案 2 :(得分:1)
如果状态列已修复,
然后你可以试试下面的东西
select id, count(distinct `status`) as ct from tab group by id having ct=3
检查Here
答案 3 :(得分:0)
也许这很有帮助:
SELECT
id,
`status`,
COUNT(tab.status) AS s
FROM
tab
GROUP BY id
HAVING s = 3