我想从MySql表中查找行,该表在两列中包含相同的值。
我的桌子就像
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的那些行。
答案 0 :(得分:1)
您可以将group by
与having
子句一起使用,如下所示
select *
from tab
where id in
(
select id
from tab
group by id
having max(status)=min(status)
)
and status!='false'
答案 1 :(得分:0)
您似乎想要not exists
:
select t.*
from t
where not exists (select 1 from t t2 where t2.id = t.id and t2.status = 'false');
答案 2 :(得分:0)
在碎石场上为时已晚,所以这只是出于旧时的缘故。
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