MySQL join based on where from 2nd table

0pizxfdo  于 2022-12-22  发布在  Mysql
关注(0)|答案(2)|浏览(156)

I have two tables as follows:

docs

idcaridname
11doc1
21doc2
32doc3
41doc4
55doc5

cars

caridparentidname
14car1
25car2
34car3
44car4
55car5

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.

kt06eoxx

kt06eoxx1#

You need to join the cars -table twice. First for the condition and second for the parent:

select d.*
from cars c
  join cars p on p.parentid=c.parentid
  join docs d on d.carid=p.carid
where c.carid=3
3bygqnnd

3bygqnnd2#

You're thinking about this a little wrong in the aspect of a relational database .. You SHOULD have 4 tables:

docs

doc_idname
1doc1
2doc2
3doc3
4doc4
5doc5

cars

car_idname
1car1
2car2
3car3
4car4
5car5

cars_to_docs

car_iddoc_id
11
12
14
23
55

parents_to_car

car_idparent_id
14
25
34
44
55

Then you could simply use a basic JOIN

SELECT b.doc_id FROM test.docs a

LEFT JOIN test.cars_to_docs b
ON a.doc_id = b.car_id

LEFT JOIN test.parents_to_car c
ON c.car_id = b.car_id

LEFT JOIN test.cars d
ON c.car_id = d.car_id

WHERE c.parent_id = (SELECT parent_id FROM test.parents_to_car WHERE car_id = 3)

This will give you your output of 1,2,4

相关问题