SQL: Return only records without any associations that meet criteria

时间:2015-07-29 00:31:30

标签: mysql sql

How can I return only the records that do not have any associated records that meet a certain criteria?

For example, if I have a one to many relationship between users and addresses, how can I get all the users who do NOT have a specific city in their address history?

SQL Fiddle here

Example data here:

domain

1 个答案:

答案 0 :(得分:1)

The simplest way is with String or not exists:

left join

The select u.* from users u left join addresses a on a.username = u.username and a.city = 'Peoria' where a.city is null; keeps all records in users and any records in left join that match the addresses conditions. In this case (because the city name is in the on condition), it returns all users with either information about the cities or on values. The NULL clause chooses the where values -- the non-matching ones.

The equivalent NULL might be easier to follow:

not exists