mysql 在查詢和更新sql中都可以進行判斷,下面根據我這兩條sql看下case when和ifnull的用法:
case when
update t_tradefee set margin_profit = (case when market_price is null
then (2.3-basic_fee)*remain_amount
else (2.3-market_price)*remain_amount+margin_profit END),
market_price = 2.3 where substring(cardno,1,3)='001' and trade_type = 1
更新過程中的判斷,如果market_price
為空則set margin_profit的值為(2.3-basic_fee)*remain_amount
,否則 set margin_profit的值為2.3-market_price)*remain_amount+margin_profit
用法:case when… else… end
ifnull
select day(op_time) as day,sum(price) as price,
IFNULL((select sum(price) from t_margin_profit where op_time<'2016-1-1 00:00:00' ),0) as old
from t_margin_profit
where year(op_time)='2016' and month(op_time)='1' GROUP BY day(op_time)
查詢中的判斷賦值操作
用法:IFNULL(exp1,exp2) : 如果exp1的值不為空,取exp1的值,否則取exp2的值。