I have three tables in the many-to-many format. I.e, table A, B, and AB set up as you’d expect.
Given some set of A ids, I need to select only the rows in AB that match all of the ids.
Something like the following won’t work:
‘SELECT * FROM AB WHERE A_id = 1 AND A_id = 2 AND A_id = 3 AND … ‘ As no single row will have more than one A_id
Using, an OR in the sql statment is no better as it yields results all results that have at least one of the A ids (whereas I only want those rows that have all of the ids).
Edit:
Sorry, I should explain. I don’t know if the actual many-to-many relationship is relevant to the actual problem. The tables are outlined as follows:
Table People int id char name Table Options int id char option Table peoples_options int id int people_id int option_id
And so I have a list of people, and a list of options, and a table of options and people.
So, given a list of option ids such as (1, 34, 44, …), I need to select only those people that have all the options.
A bit of a hacky solution is to use IN with a group by and having filter. Like so:
That way, you only get the B_id values that have exactly 3 A_id values, and they have to be from your list. I used DISTINCT in the COUNT just in case (A_id, B_id) isn’t unique. If you need other columns, you could then join to this query as a sub-select in the FROM clause of another select statement.