简体   繁体   中英

SQL Select where all related entries satisfy condition

Table A:

id | name | type 

Table B:

id | a_id | structure

where A has many B's.

I would like to query for all As where none of it's related entries in Table B has a structure = 'successful'

I am attempting to do

select a.name
from a
inner join b on a.id = b.a_id where a.type = 'note' and a.id = ALL (Select a_id from B where structure <> 'successful')

but I am getting 0 results. (Heroku Dataclips)

Sample Data

id | name | type
01 | woof | note
02 | meow | note
03 | who  | free

id | a_id | structure
01 | 01 | open
02 | 01 | draft
03 | 02 | draft
04 | 02 | successful
05 | 02 | open
06 | 03 | open

Running this query should return

woof

since I want all entities from A that has an associated type of note, but that none of it's related entries in table B has a structure = 'successful'

A simple not exists would satisfy your criteria?

select a.name
from TableA a
where a.type='note'
and not exists (select * from TableB b where b.a_id=a.id and b.structure='successful')

Result: 'woof'

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