I have two tables as follows:
docs
id | carid | name |
---|---|---|
1 | 1 | doc1 |
2 | 1 | doc2 |
3 | 2 | doc3 |
4 | 1 | doc4 |
5 | 5 | doc5 |
cars
carid | parentid | name |
---|---|---|
1 | 4 | car1 |
2 | 5 | car2 |
3 | 4 | car3 |
4 | 4 | car4 |
5 | 5 | car5 |
Question: I want to write a query in mysql where I can pass the carid in where clause and get all the rows from docs table where the parentid is same as that of the passed carid.
Desired Outcome If I pass carid=3 then the rows 1,2,4 from docs table should be returned as the parentid is 4 for carids 1,3,4.
Simillarly, If I pass carid=2 then the rows 3,5 from docs table should be returned as the parentid is 5 for carids 2.5.
2
Answers
You need to join the
cars
-table twice. First for the condition and second for the parent:You’re thinking about this a little wrong in the aspect of a relational database .. You SHOULD have 4 tables:
docs
cars
cars_to_docs
parents_to_car
Then you could simply use a basic JOIN
This will give you your output of 1,2,4