mysql 中的case when 和ifnull判断

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的值。

你可能感兴趣的:(mysql,判断,ifnull,case-when)