简体   繁体   中英

SQL: Find all rows in a table for which all rows in another table that refer to the original row have a certain property

I have the two tables, challenges and contestants. Contestants have an id, a challenge_id, and a user_id column.

Given a set of user ids, I want to find the set of challenges such that a challenge is in the set if all contestants whose challenge_ids are equal to the challenge's id have a user_id in the given set of user ids.

I feel like I need some sort of an IN ALL statement, but of course, that doesn't exist.

Any ideas on how to find that list of rows?

Isn't this the same as "find the set of challenges where all contestants with that challenge_id are in the given set of user ids.",

to find a set where ALL rows meet some condition, you need only find the set where No member does NOT meet the condition, so this is the same as:

"find the set of challenges where there are NO contestants with that challenge_id who are NOT in the given set of user ids.",

Select distinct challenge_Id
From Contestents c
Where Not exists (Select * From Contestents 
                  Where challenge_Id = c.challenge
                     And user_id not In ([List of UserIds]))

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