我怎样才能获得具有所有状态的id?

时间:2018-04-01 07:20:21

标签: mysql sql

我有一个包含两列的数据库表:idstatus

status可以有三个不同的值,ABC

我现在希望获得具有所有三种不同状态(idAB)的C个。

id status
 1 A
 2 A
 1 B
 3 A
 3 B
 3 C

4 个答案:

答案 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