简体   繁体   中英

MySql: How to select rows where all values are the same?

I have a table like this:

name |id | state
name1 12   4
name1 12   4
name2 33   3
name2 33   4
...

I want to select every name and id from table where state is only 4, that means name1 is correct, because it only has two records with state 4 and nothing more. Meanwhile name2 is wrong, because it has record with state 4 and record with state 3.

select name, id from mytable where id not in
(select distinct id from mytable where state <> 4)

You can use aggregation as shown below:

SELECT name, id
FROM your_table
GROUP BY name, id
HAVING SUM(state<>4)=0;

See a Demo on SQL Fiddle .

you might need 2 sub queries .

  1. select with group by name were state 4
  2. select with group by name

compare the count if the count is same then select it

example : select name , count (name) from table where state = 4 as T1 select name , count (name) from table as T2 select T1.name from T1 and T2 where T2.count = T1.count

You can use not exists like this:

select distinct name, id 
from table1 a
where not exists (select *
                  from table1 b
                  where  a.id=b.id and state<>4)

In a more general case you can use count distinct (with not exists or with a join):

select distinct name, id 
from table1 a
where not exists (
select *
from table1 b
where  a.id=b.id
group by id
HAVING count(distinct state)>1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM