选择mysql字段取决于其他字段值

时间:2013-09-26 14:04:49

标签: mysql relational-database

我有3张桌子:

currency
id | name
1  | usd
2  | eur

currency_date
id |   date   | usd | eur
1  | 22.09.13 | 10  | 12
2  | 23.09.13 | 11  | 13
3  | 24.09.13 | 9   | 10

cost
id | id_currency | id_currency_date | cost
1  |     1       |       2          |  15

因此,对于cost表中 id = 1 的行,我们usd的交换值为11

是否可以通过不同表中其他字段的名称获取字段值?

我认为它必须是这样的:

SELECT currency_date.VAR(currency.name) AS cur_val
FROM cost
LEFT JOIN currency ON currency.id = cost.id_currency
LEFT JOIN currency_date ON currency_date.id = cost.id_currency_date
WHERE cost.id = 1

currency_date.VAR(currency.name)仅用于显示我想要的内容。

1 个答案:

答案 0 :(得分:2)

这应该这样做。

SELECT case currency.name when 'usd' then currency_date.usd when 'eur' then currency_date.eur end AS cur_val
FROM cost
LEFT JOIN currency ON currency.id = cost.id_currency
LEFT JOIN currency_date ON currency_date.id = cost.id_currency_date
WHERE cost.id = 1