SQL:如何多次加入同一个表?

wra*_*wra 2 mysql sql select join left-join

我有两个表,我需要为两个不同的列两次加入第二个表。表格采用以下格式:

表 1:trip_details

column            type
name              string
start_country_id  int
end_country_id    int
Run Code Online (Sandbox Code Playgroud)

表 2:country_info

column   type
id       int
country  string
Run Code Online (Sandbox Code Playgroud)

我想获得名称、起始国家和结束国家。

这将是我的尝试:

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
Run Code Online (Sandbox Code Playgroud)

据我所知,问题出在连接上,因为我在 Select 子句中使用了两次“country_info.country”。这些情况的最佳方法/做法是什么?

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

Mur*_*nik 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
Run Code Online (Sandbox Code Playgroud)