选择mysql字段取决于其他字段值
我有三张桌子:选择mysql字段取决于其他字段值,mysql,relational-database,Mysql,Relational Database,我有三张桌子: 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 | 1
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\u date.VAR(currency.name)仅用于显示我想要的内容。这应该可以
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
如果您规范化了数据,并且在currency_date表中为每种货币提供单独的记录,那么效果会更好。然后一个简单的连接就可以了。如果不能规范化,可以硬编码一个解决方案。你希望在未来增加很多货币吗?谢谢,这很有效。。。只需编辑一些语法正确的代码。