MySQL在匹配特定值时加入条件

时间:2016-03-05 10:43:52

标签: mysql sql join left-join

我有一个包含表countriesexchange_rates

的MySQL数据库
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 |
+----------+------+

我希望有一个联合表格,其中附加列显示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 |
+----------------+----------------+----------------+

但是,我想另外表明:

  • 以当地货币计算的国内生产总值,即使缺少汇率信息
  • 拥有当地货币的国家的GDP'美元'在两栏中

所需的输出是:

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

我将非常感谢你的帮助。

3 个答案:

答案 0 :(得分:3)

使用left join包含汇率缺失的国家/地区,并使用案例表达式将美国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;

此外,我更改为正确的连接并为表添加了别名以缩短查询。

答案 1 :(得分:2)

要获得#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表中添加一张速率为1的美元记录。如果您不想在表格中填写,请在查询中执行此操作:

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;

答案 2 :(得分:1)

其他答案都很好,但我会把它写成:

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()是最简单的方法。 。 。假设唯一缺失的汇率是美元。