如何从多个列中从sql中查找重复记录

xpcnnkqh  于 2021-06-15  发布在  Mysql
关注(0)|答案(3)|浏览(291)

我想从mysql表中查找行,该表在两列上包含相同的值。
我的table像

ID   NAME   EMAIL         Status
1    John   asd@asd.com   True
1    Sam    a@gmail.com   False
2    Tom    b@gmail.com   True
2    Bob    bob@asd.com   true
3    Jam    8@gmail.com   False
3    Mam    7@gmail.com   False
5    Tom    a23@asd.com   True

所以,我需要上表中的数据,如果它重复,则具有相同的id和状态,否则它应该给我具有单个id的数据,并且状态=true。结果如下:

ID   NAME   EMAIL         Status 
2    Tom    b@gmail.com   True
2    Bob    bob@asd.com   true
5    Tom    a23@asd.com   True

这意味着,我只需要那些status=true且id相同的行。

hfyxw5xn

hfyxw5xn1#

在砾石坑太晚了,所以这只是为了过去。

DROP TABLE IF EXISTS BEDROCK;
CREATE TABLE BEDROCK (ID INT, NAME VARCHAR(100), EMAIL VARCHAR(100), `Status` VARCHAR(6));

INSERT INTO BEDROCK (ID, NAME, EMAIL, `Status`) VALUES
(1,'Fred','fred.flintstone@stone.age','True'),
(1,'Wilma','wilma.flintstone@stone.age','False'),
(2,'Barney','barney.rubble@stone.age','True'),
(2,'Betty','betty.rubble@stone.age','True'),
(3,'Pebbles','pebbles.flintstone@stone.age','False'),
(3,'Bamm-Bamm','bamm-bamm.rubble@stone.age','False'),
(5,'Dino','dino@stone.age','True');

SELECT *
FROM BEDROCK t1
WHERE `Status` = 'true'
AND NOT EXISTS
(
  SELECT 1
  FROM BEDROCK t2
  WHERE t2.`Status` = 'false'
    AND t2.ID = t1.ID
);

结果:

ID  NAME    EMAIL                   Status
--  ------  ----------------------- ------
2   Barney  barney.rubble@stone.age True
2   Betty   betty.rubble@stone.age  True
5   Dino    dino@stone.age          True
a7qyws3x

a7qyws3x2#

你可以用 group byhaving 条款如下

select *
  from tab
 where id in
 (
  select id
    from tab
   group by id
  having max(status)=min(status)
 ) 
   and status!='false'

rextester演示

3mpgtkmj

3mpgtkmj3#

你好像想要 not exists :

select t.*
from t
where not exists (select 1 from t t2 where t2.id = t.id and t2.status = 'false');

相关问题