【问题标题】:SQL joins on joined table连接表上的 SQL 连接
【发布时间】:2019-03-04 15:49:31
【问题描述】:

table1

out_path_id
in_path_id
other_fields

table2

id
name
location_to_id
location_from_id
car_id
other_fields

位置

id
name

汽车

id
name

table1out_path_idin_path_id是指table2id

table2location_to_idlocation_from_id是指locationid

table2car_id是指carid

可以加入table1table2

select t2out.name out_name, t2in.name in_name, t1.other_fields
from table1 t1
join table2 t2out on t2out.id=t1.out_path_id
join table2 t2in on t2in.id=t1.in_path_id 

现在我尝试继续加入locationcar。我能做些什么?

【问题讨论】:

  • 请更新描述以显示您期望结果集的样子;这是了解连接应该如何工作的必要条件。

标签: sql sqlite join


【解决方案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

【讨论】:

  • 谢谢,但是好像不行,找不到location_from_id属于哪个表:ambiguous column name: location_from_id
  • 先加入table2locationcar 怎么样,然后加入table1
【解决方案2】:

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

JOIN location t2out_loc_to ON t2out.location_to_id = t2out_loc_to.id

等等

【讨论】:

    猜你喜欢
    • 2012-08-15
    • 2013-07-21
    • 2018-05-11
    • 2013-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多