SQL:如何多次连接同一张表?

3
我有两个表格,需要根据两列信息分别将第二个表格连接两次。这两个表格的格式如下:
表格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

根据我的观察,问题出在连接上,因为我在选择子句中两次使用了“country_info.country”。在这种情况下,最好的方法/实践是什么呢?

编辑:
不确定是否还有其他方法可以做到这一点,但这只是我的SQL查询的一部分,所以我确实需要使用LEFT JOIN。


此问题非常相似,只相差半小时! - HoneyBadger
@HoneyBadger 为什么不呢?这只是无休止的未经研究的重复之流中的一部分。 - philipxy
嗨。下次请努力谷歌你的问题,例如你当前的标题,这样你就不会再问一个重复的问题了。另外请参见[mcve]。 - philipxy
1个回答

6
拥有两个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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接