简体   繁体   中英

How can I select all non-unique field1s where field2 is never x?

Given the dataset below:

field1 field2
a      1
a      2
a      3
b      1
b      2
b      4
c      2
c      2
c      3

How can I determine which values for field1 are never associated anywhere in the table with a field2 value of 4?

The result would be

field1
a
c

SELECT field1 FROM table WHERE field2 <> 4 will include b because it appears in the table multiple times with other field2 values - how do I prevent this?

You can group by field1 and put the condition in the having clause:

select field1
from tablename
group by field1
having sum(field2 = 4) = 0

use not exists

select t1.* from table t1
where not exists( select 1 from table t2 where t1.field1=t2.field1 
                 and t2.field2=4)

or use not in

select * from table t1
where t1.field1 not in ( select field1 from table where field2=4)

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