SQL query to find users that don't have any subscription to a specified list (many-to-many)
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 use开发者_如何学运维rs that have no subscriptions at all)?
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
)
I used NOT IN
and it works well:
SELECT Count(*)
FROM "users"
WHERE "users"."id" NOT IN (SELECT "users"."id"
FROM "users"
INNER JOIN "unsubscribes"
ON "unsubscribes"."user_id" =
"users"."id"
WHERE "unsubscribes"."list" = $1)
Ruby on Rails scopes as a bonus:
scope :unsubscribed, -> (list) { joins(:unsubscribes).where(unsubscribes: { list: list }) }
scope :subscribed, -> (list) { where.not(id: User.unsubscribed(list)) }
精彩评论