sql:过滤出列值多次出现的行

nzk0hqpo  于 2021-06-15  发布在  Mysql
关注(0)|答案(5)|浏览(360)

我有一个mysql表,如下所示:

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

因此,一个给定的 id 可以有多个 label s。我只想保留 id 有一个单身汉 label . 因此上表的正确输出是:

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

我在想我应该分组 id 并找出每个标签的数量 id . 那我就只取一行。

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

看起来很近吗?
谢谢!

t0ybt7op

t0ybt7op1#

您可以仅使用联接来包含在子查询中出现一次的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
              );
cgvd09ve

cgvd09ve2#

你可以试试这个:

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;
prdp8dxp

prdp8dxp3#

假设两人 id 以及 label 是独一无二的,你可以用 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);
czq61nw1

czq61nw14#

是的,您的方法是正确的,您可能需要更改having count条件,并且在引用cte时,您可能需要稍微更改您的语法,但是您也可以在没有cte的情况下使用exists条件在同一行中完成。

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
zbq4xfa0

zbq4xfa05#

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

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

相关问题