SQL在联接表上联接

时间:2019-03-04 15:49:32

标签: sql sqlite join

表1

out_path_id
in_path_id
other_fields

表2

id
name
location_to_id
location_from_id
car_id
other_fields

位置

id
name

汽车

id
name

table1的{​​{1}}和out_path_id是指in_path_id的{​​{1}}。

table2的{​​{1}}和id是指table2的{​​{1}}。

location_to_id的{​​{1}}是指location_from_id的{​​{1}}。

可以加入locationid

table2

现在,我尝试继续加入car_idcar。我能做什么?

2 个答案:

答案 0 :(得分:1)

尝试使用下面的相应键,将位置和汽车同时加入

select t1.other_fields,t2.name as out_name,
     t22.name as in_name,l1.name as location_to_name
    ,l2.name as location_from_name,c.name from 
      table1 t1
      left join table2 t2 on t1.out_path_id=t2.id
      left join table2 t22 on t1.in_path=t22.id
      left join location l1 on t2.location_to_id=l1.id
      left join location l2 on t2.location_from_id=l2.id
      left join car c on t2.car_id=c.id

答案 1 :(得分:0)

您将像以前一样继续使用别名。您需要4个位置表别名,因为table2中有两个位置。您将需要两个赛车表别名,因为表2中有1辆车。

JOIN location t2out_loc_to ON t2out.location_to_id = t2out_loc_to.id

等等

相关问题