我有两个表,对于两个不同的列,我需要两次连接第二个表。这些表的格式如下:
表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
关于mysql - SQL:如何多次连接同一张表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48722297/