MySQL 匹配特定值时加入条件

MySQL Join with condition when matching certain value

我有一个 MySQL 数据库 tables countriesexchange_rates:

mysql> SELECT * FROM countries;
+----------------+----------+----------------+
| name           | currency | GDP            |
+----------------+----------+----------------+
| Switzerland    | CHF      |   163000000000 |
| European Union | EUR      | 13900000000000 | 
| Singapore      | SGD      |   403000000000 |
| USA            | USD      | 17400000000000 |
+----------------+----------+----------------+
mysql> SELECT * FROM exchange_rates;
+----------+------+
| currency | rate |
+----------+------+
| EUR      |  0.9 |
| SGD      | 1.37 |
+----------+------+

我想要一个加入的 table 附加列以美元显示 GDP。

目前我有这个:

mysql> SELECT countries.name, GDP, countries.GDP/exchange_rates.rate AS 'GDP US$'
    -> FROM countries, exchange_rates
    -> WHERE exchange_rates.currency=countries.currency;
+----------------+----------------+----------------+
| name           | GDP            | GDP US$        |
+----------------+----------------+----------------+
| European Union | 13900000000000 | 15444444853582 |
| Singapore      |   403000000000 |   294160582917 |
+----------------+----------------+----------------+

不过,我想另外说明一下:

期望的输出是:

+----------------+----------------+----------------+
| name           | GDP            | GDP US$        |
+----------------+----------------+----------------+
| European Union | 13900000000000 | 15444444853582 |
| Singapore      |   403000000000 |   294160582917 |
| Switzerland    |   163000000000 |                |
| USA            | 17400000000000 | 17400000000000 |
+----------------+----------------+----------------+

我将不胜感激。

为了获得#1,您只需要使用 left join 而不是内部连接:

SELECT countries.name, GDP, countries.GDP/exchange_rates.rate AS 'GDP US$'
  FROM countries LEFT JOIN exchange_rates
  ON exchange_rates.currency=countries.currency;

为了获得#2,只需在 exchange_rate table 中添加一条汇率为 1 的美元记录。如果您不希望它出现在 table 中,请执行它在查询中:

SELECT countries.name, GDP, countries.GDP/full_exchange_rates.rate AS 'GDP US$'
  FROM countries LEFT JOIN (
   select currency, rate from exchange_rates
    union
   select 'USD' as currency, 1 as rate 
  ) as full_exchange_rates
ON full_exchange_rates.currency=countries.currency;

使用 left join 包含缺少汇率的国家,并使用 case 表达式始终将美国 GDP 设置为美国 GDP:

SELECT 
    c.name, 
    GDP, 
    CASE WHEN c.name = 'USA' THEN c.GDP ELSE c.GDP/er.rate END AS 'GDP US$'
FROM countries c
LEFT JOIN exchange_rates er ON er.currency = c.currency;

此外,我更改为适当的连接并为表添加了别名以稍微缩短查询。

其他答案都很好,但我会这样写:

SELECT c.name, c.GDP, c.GDP/COALESCE(er.rate, 1.0) AS "GDP US$"
FROM countries c LEFT JOIN
     exchange_rates er
     ON er.currency = c.currency;

我认为 COALESCE() 是最简单的方法。 . .假设唯一缺少的汇率是美元。