[英]SQL: How to join the same table multiple times?
我有两个表,对于两个不同的列,我需要两次连接第二个表。 这些表的格式如下:
表1:trip_details
column type
name string
start_country_id int
end_country_id int
表2:country_info
column type
id int
country string
我想获取名称,开始国家和结束国家。
这是我的尝试:
SELECT
trip_details.name AS "Name",
country_info.country AS "Start Country",
country_info.country AS "End Country"
FROM
trip_details
LEFT JOIN country_info ON country_info.id = trip_details.start_country_id
LEFT JOIN country_info ON country_info.id = trip_details.end_country_id
从我看来,问题出在联接上,因为我在Select子句中两次使用了“ country_info.country”。 这些情况的最佳方法/做法是什么?
编辑:
不知道是否有其他方法可以执行此操作,但这只是我的SQL查询的一部分,因此我需要使用LEFT JOIN
拥有两个join
子句是正确的方法。 您只是想给它们提供不同的别名以区别两者:
SELECT td.name AS "Name",
sci.country AS "Start Country",
eci.country AS "End Country"
FROM trip_details td
LEFT JOIN country_info sci ON sci.id = td.start_country_id
LEFT JOIN country_info eci ON eci.id = td.end_country_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.