我有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)仅用于显示我想要的内容。
答案 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