SQL:筛选出列值多次出现的行

时间:2019-01-06 18:57:50

标签: mysql sql

我有一个如下所示的MySQL表:

id    |    label
----------------
1          "john"
1          "henry"
1          "sara"
2          "henry"
3          "tim"

因此,给定的id可以有多个label。我只想保留id有一个label的行。因此,上表的正确输出为:

id    |    label
----------------
2          "henry"
3          "tim"

我当时想我应该按id分组,并找到每个id的标签数。然后,我只接受计数为1的行。

WITH temp as
(SELECT id
FROM original_table
GROUP BY id
HAVING COUNT(id) > 5)

SELECT *
FROM original_table ot
WHERE ot.id in temp.id

那看起来很近吗?

谢谢!

5 个答案:

答案 0 :(得分:1)

您可以仅使用联接仅包含在子查询中出现一次的ID:

SELECT  id,
        label
  FROM  original_table ot
    INNER JOIN  (
                SELECT  id
                  FROM  original_table
                  GROUP BY id
                  HAVING COUNT(*) = 1
                ) a ON a.id = ot.id;

或者您可以使用IN子句:

SELECT  id,
        label
  FROM  original_table
  WHERE id IN (SELECT   id
                  FROM  original_table
                  GROUP BY id
                  HAVING COUNT(*) = 1
              );

答案 1 :(得分:1)

我认为聚合是最简单的方法:

select id, min(label) as label
from original_table t
group by id
having count(*) = 1;

答案 2 :(得分:0)

您可以尝试以下方法:

SELECT t.id, t.label
FROM tbl AS t
JOIN (SELECT id FROM tbl GROUP BY id HAVING count(label) = 1) AS t1
ON t.id = t1.id;

答案 3 :(得分:0)

假设idlabel对是唯一的,则可以使用NOT EXISTS和相关的子查询。

SELECT t1.id,
       t1.label
       FROM original_table t1
       WHERE NOT EXISTS (SELECT *
                                FROM original_table t2
                                WHERE t2.id = t1.id
                                      AND t2.label <> t1.label);

答案 4 :(得分:0)

是的,您的方法是正确的,您可能必须更改您的计数条件,而在引用CTE时,您可能只需要稍微更改语法,但是在没有CTE的情况下,也可以在存在条件的同一行中进行更改。

Create table  temp  (ID int , Label varchar(10)); 

insert into  temp values 
(1  ,      "john" ), 
(1   ,     "henry" ) , 
(1   ,     "sara" )  , 
( 2   ,    "henry"  ) , 
(3   ,     "tim" ) ; 


select t.ID , t.Label from temp t 
where exists (
select ID, count(1) Dups  from temp t1 where t1.ID = t.ID group by ID having count(1) 
= 1) 

输出:

    ID, Label
    2, henry
    3, tim