Having two tables, "users" and "lists", and a many-to-many "subscriptions" table relating users to lists (thus having foreign keys user_id
and list_id
), what would be a single SQL query to find all the users that don't have any subscription with a specific list_id
(naturally including the users that have no subscriptions at all)?
views:
95answers:
1
+2
A:
Time to break out not exists
again:
select
u.user_id
from
users u
where
not exists (
select 1 from subscriptions s where s.user_id = u.user_id and s.list_id = N
)
Donnie
2009-12-02 15:55:29
Works perfectly, thanks! Never heard of `exists` before.
Sergei Kozlov
2009-12-02 16:06:18