Skip to content

Query an AND in a many-to-many table

I know that this is a relatively simple question, I just can’t figure it out. I have three tables: people, presentations, and people_presentations. people and presentations both have ID columns, and people_presentations that has foreign keys to each of people and presentations.

For example:

people:

presentations:

people_presentations:

I am trying to select all presentation IDs where a specific subset of people is attached. For ORs this is relatively easy: SELECT DISTINCT presentation_ID FROM people_presentations WHERE people_ID IN (1,2);, but for the AND case… I just can’t figure it out. This needs to work for N people, so I’d rather not have infinite JOINs.

Advertisement

Answer

You can filter the table for the people that you want, group by presentation and set the condition in the HAVING clause:

See the demo.

User contributions licensed under: CC BY-SA
9 People found this is helpful