mysql> select * from person; +----+---------+--------+------+--------+ | id | country | name | age | gender | +----+---------+--------+------+--------+ | 3 | china | tim | 10 | 1 | | 7 | usa | kobe | 10 | 1 | | 8 | usa | james | 20 | 1 | | 9 | usa | grace | 30 | 0 | | 10 | japan | monica | 40 | 2 | +----+---------+--------+------+--------+
查询
1 2 3 4 5 6 7 8 9 10
mysql> SELECT id, `name`, CASE gender WHEN 1 THEN '男' WHEN 0 THEN '女' ELSE '其他' END AS gender FROM person; +----+--------+--------+ | id | name | gender | +----+--------+--------+ | 3 | tim | 男 | | 7 | kobe | 男 | | 8 | james | 男 | | 9 | grace | 女 | | 10 | monica | 其他 | +----+--------+--------+
分组统计
根据不同国家统计用户的性别
1 2 3 4 5 6 7 8 9 10 11 12 13
mysql> select country, -> sum(case when gender=1 then 1 else 0 end) as male, -> sum(case when gender=0 then 1 else 0 end) as female, -> sum(case when gender>1 then 1 else 0 end) as unknown -> from person -> group by country; +---------+------+--------+---------+ | country | male | female | unknown | +---------+------+--------+---------+ | china | 1 | 0 | 0 | | japan | 0 | 0 | 1 | | usa | 2 | 1 | 0 | +---------+------+--------+---------+
更新
简单Case函数
1 2 3 4 5 6 7 8
UPDATE person SET`status` = CASEid WHEN1THEN1 WHEN2THEN0 WHEN3THEN0 WHEN4THEN1 END WHEREidIN (1, 2, 3, 4)
注意事项:一定要有 WHERE id IN 的限制,否则不在 WHEN 中的记录就会被置为 NULL
Case搜索函数
1 2 3 4 5
UPDATE person SET`status` = CASE WHENid%2=1THEN1 WHENid%2=0THEN0 END
区别:简单Case函数只能实现相等条件判断,Case搜 索函数适合复杂条件判断,比如大于、小于等
条件查询
1 2
SELECT * FROM person WHERECASEname="" THER trueELSEname="lp"
删除
1 2 3 4 5
DELETEFROM person WHERE (CASE WHEN country IN ('chain', 'usa') THEN0 ELSEDATEDIFF(CURDATE(), timestamp) > 365 END);