简体   繁体   中英

Select records with one-to-many relationship where all of the many are in a list

I have a table of records with a one to many relationship to another table. I want to return all records in the first table where ALL entries in the second table are found in a comma separated list.

Client   ClientData                   Client    Project
John                                  John      1
Jane                                  Jane      2
Mary                                  Mary      3
Randy                                 John      4
                                      Mary      5
                                      Randy     6
                                      Jane      7

So, if my list is (1, 2, 3, 4, 5) Then I want to return Client and ClientData for John and Mary. Jane has one entry in the list, but not all so I don't want her returned.

SELECT DISTINCT c.*
FROM ClientData c
INNER JOIN ProjectData pd
    ON c.client_name = pd.client_name AND pd.project_id IN (1,2,3,4,5)
WHERE c.client_name NOT IN (
    SELECT client_name FROM ProjectData WHERE project_id NOT IN (1,2,3,4,5)
)

Also, I would hope you are using a unique identifier for your clients instead of just a name.

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