i have a problem with sql request. I have 3 tables.
table_1
id | name |
---|---|
1 | aaa |
2 | bbb |
3 | ccc |
4 | ddd |
table_2
id | name |
---|---|
1 | zzz |
2 | yyy |
3 | xxx |
4 | www |
And third table for many to many relationship.
table_1_table_2
table_1_id | table_2_id |
---|---|
1 | 1 |
1 | 2 |
3 | 3 |
4 | 4 |
In request i have 2 id from table 2.
And finally my question.
How to find row from table_1 which have relationship with two row in table_2?
SELECT * FROM `table_1`
JOIN `table_1_table_2` ON table_1.id=table_1_table_2.table_1_id
JOIN `table_2` ON table_2.id=table_1_table_2.table_2
WHERE table_2.id = 1 AND table_2.id = 2
3
Answers
try this:
it is impossible to have a row with two different ids in the same column
perhaps you meant:
You don’t need to join all tables. It’s sufficient to use the relationships table to count amount of id2 for each id1, then join with tab1 if you want to gather id1 names.
Output:
Check the demo here.