如何在一个 SQL 查询中替换多列?

How to replace multiple columns in one SQL query?

我有 2 个 table:countrytrip

一次旅行最多可以有 3 个国家代码。

国家 table

country_code country_name
FRA FRANCE
IRL IRELAND
JPN JAPAN
MAR MOROCCO
NZL NEW ZEALAND

旅行 table

trip_id country_code country_code2 country_code3
1 FRA IRL JPN
2 MAR NZL

我的目标是在旅行中显示国家名称 table 而不是国家代码。

由于左连接子句,我成功地只替换了 1 个国家代码。我希望每行最多显示 3 个国家名称。

SELECT trip_id, country_name
FROM trip
LEFT JOIN country ON country_code = country_name

行程实际输出table:

trip_id country_name
1 FRANCE
2 MOROCCO

有没有办法用相应的国家名称替换每个国家代码?

来自 trip table 的查询的预期输出:

trip_id country_name country_name2 country_name3
1 FRANCE IRELAND JAPAN
2 MOROCCO NEW ZEALAND

谢谢!

您可以再添加两个联接

SELECT trip_id, c1.country_name, c2.country_name, c3.country_name
FROM trip t
left join 
country c1
on t.country_code = c1.country_code
left join 
country c2
on t.country_code2 = c2.country_code
left join 
country c3
on t.country_code3 = c3.country_code

完成此查询的最简洁方法是使用子查询:

SELECT t.trip_id, 
       (SELECT country_name FROM country WHERE country_code =  t.country_code) "c1",
       (SELECT country_name FROM country WHERE country_code = t.countty_code2) "c2",
       (SELECT country_name FROM country WHERE country_code = t.country_code3) "c3"
FROM trip t