语法是CASE expressing WHEN condition THEN return
这里expressing 不是必须的,如果有,就是拿来和condition进行比较的,意即如果有expressing,默认将它和WHEN后面的条件进行=比较,如果真,返回THEN后面的结果。下面是有expressing和没有expressing的两种写法:
或者,我们可以用if方法
if的语法是IF(condition, value_if_true, value_if_false)
在项目开发中,我们常常会用到根据不同条件,执行不同的sql,在mysql中可以用 IF(expr1,expr2,expr3) 来满足这个需求。下面我给大家一个示例:
示例1:sql比较复杂
SELECT
if(dom.PLAN_NO is null,
(ifnull( ( SELECT sum( DELIVERY_QTY ) FROM delivery_order_materiel WHERE 1=1 and PO_NO=pom.PO_NO and MATERIEL_CODE = pom.MATERIEL_CODE ), 0 )),
ifnull( ( SELECT sum( DELIVERY_QTY ) FROM delivery_order_materiel WHERE POM_PM_CODE = pom.PM_CODE AND PLAN_NO = dpm.PLAN_NO ), 0 )
)AS tempFiled
from tableName
where 1=1
示例2:
SELECT
if(dom.PLAN_NO=1,
( SELECT sum( DELIVERY_QTY ) FROM delivery_order_materiel WHERE 1=1 and PO_NO=pom.PO_NO and MATERIEL_CODE = pom.MATERIEL_CODE ),
( SELECT sum( DELIVERY_QTY ) FROM delivery_order WHERE 1=1 AND PLAN_NO = dpm.PLAN_NO )
)AS tempFiled
from tableName
where 1=1
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)