具有某些IF ELSE的Mysql查询如果ELSE条件

时间:2016-08-29 12:16:32

标签: mysql if-statement case

Iam尝试使用某些if条件编写mysql查询。

我的数据库结构

货币(表)

++++++++++++++++++++++++++
id | currency | rate
++++++++++++++++++++++++++
1      USD       1
2      INR       67.10043
3      GBP       0.761203
4      EUR       0.89295
++++++++++++++++++++++++++

com_payments (Table)
++++++++++++++++++++++++++
id | amt_curr | amt_paid
++++++++++++++++++++++++++
1      EUR        300.89
2      GBP        390.90
3      USD        600.00
++++++++++++++++++++++++++

我正在寻找的查询是

if (amt_curr=='USD') {
    $totalinr = (amt_paid * rate); (rate it should take from currency table where currency='USD' from currency table)
} else if ($currency1=='GBP'){
    totalinr = ((select currency, rate from Currency where currency=INR / 0.761203 (GBP value from currency table)) * amt_paid);
} else if ($currency1=='EUR'){
    totalinr = ((select currency, rate from Currency where currency=INR / 0.89295 (EUR value from currency table)) * amt_paid); 
}

我试图用mysql查询来实现这个目的:我尝试了类似这样的东西,但它不起作用:

CASE WHEN (amt_curr=='USD') THEN (amt_paid * rate) (rate it should take from currency table where currency='USD' from currency table)
     WHEN ($currency1=='GBP') THEN ((select currency, rate from Currency where currency=INR / 0.761203 (GBP value from currency table)) * amt_paid) 
     WHEN ($currency1=='EUR') THEN ((select currency, rate from Currency where currency=INR / 0.89295 (EUR value from currency table)) * amt_paid)
END AS totalinr

2 个答案:

答案 0 :(得分:0)

您只需要一个join。实际上,您的查询缺少select。我怀疑这可以做你想要的:

select p.*,
       p.amt_paid / c.rate
from com_payments p left join
     currency c
     on c.currency = p.amt_currency;

这会将所有值转换为美元(基于汇率)。如果您愿意,可以使用类似的逻辑转换任何其他货币。

答案 1 :(得分:0)

这可以通过联接完成,您不需要使用CASE EXPRESSION

SELECT t.*,
       t.amt_paid /  c.rate
FROM com_payments t
INNER JOIN currency c
 ON(c.currency = p.amt_currency)

修改

SELECT t.*,
       CASE WHEN c.currency = 'USD' THEN t.amt_paid * c.rate --By the way, you can use only amt_paid since rate is always 1
                                    ELSE t.amt_paid / c.rate
       END
FROM com_payments t
INNER JOIN currency c
 ON(c.currency = p.amt_currency)