转载请注明出处:
简单CASE语句仅允许您将表达式的值与一组不同的值进行匹配。 为了执行更复杂的匹配,如范围,您可以使用可搜索CASE语句。
可搜索CASE语句等同于IF语句,但是它的构造更加可读。以下说明可搜索CASE语句的语法:
CASE
WHEN condition_1 THEN commands
WHEN condition_2 THEN commands
...
ELSE commands
END CASE;
mysql评估求值WHEN子句中的每个条件,直到找到一个值为TRUE的条件,然后执行THEN子句中的相应命令(commands)。
如果没有一个条件为TRUE,则执行ELSE子句中的命令(commands)。如果不指定ELSE子句,并且没有一个条件为TRUE,MySQL将发出错误消息。
实例:
SELECT CASE u.playerType WHEN ‘1‘ THEN u.num ELSE 0 END AS ‘livePlayCount‘, CASE u.playerType WHEN ‘2‘ THEN u.num ELSE 0 END AS ‘vodPlayCount‘, CASE u.playerType WHEN ‘1‘ THEN u.flowNum ELSE 0 END AS ‘liveFlow‘, CASE u.playerType WHEN ‘2‘ THEN u.flowNum ELSE 0 END AS ‘vodFlow‘, 0 AS ‘storeSpace‘ , 0 AS ‘storeResidueSpace‘ FROM ( SELECT playerType, COUNT(*) AS num, ifnull(SUM(bytesSend),0) AS ‘flowNum‘ FROM tbl_player_statistics WHERE playerTime BETWEEN CONCAT(DATE_FORMAT(#{month},‘%Y-%m‘),‘-01 00:00:00‘) AND CONCAT(DATE_FORMAT(last_day(#{month}),‘%Y-%m-%d‘),‘ 23:59:59‘) GROUP BY playerType )