1. 环境:
mysql 5.7+
navcat premium数据库图形管理工具
2. 数据准备:
建表DDL SQL语句
CREATE TABLE `student` ( `stu_id` int(20) NOT NULL AUTO_INCREMENT, `stu_name` varchar(50) DEFAULT NULL COMMENT ‘学生姓名‘, `stu_age` int(3) DEFAULT NULL COMMENT ‘学生年龄‘, `stu_sex` varchar(6) DEFAULT NULL COMMENT ‘学生性别‘, `add_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ‘创建时间‘, PRIMARY KEY (`stu_id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT=‘学生表‘;
插入数据:
BEGIN; INSERT INTO `student` VALUES (1, ‘Drew‘, 21, ‘男‘, null), (2, ‘Allen‘, 22, ‘男‘, null), (3, ‘King‘, 22, ‘男‘, null); COMMIT;
数据库数据:
3. 开始重点内容:
-- ---------------------------- -- mysql中强大case语句 -- ---------------------------- SELECT CASE WHEN stu_age > 21 AND stu_age < 23 THEN 1000 WHEN stu_age >= 23 THEN 2000 ELSE stu_age END stu_age FROM student;
结果显示:
第二种演示:(关注:通过case语句处理的数据显示不用检测数据类型)
SELECT stu_id, stu_name, CASE WHEN stu_age = 21 THEN ‘二十一岁‘ WHEN stu_age = 22 THEN ‘二十二岁‘ WHEN stu_age = 23 THEN ‘二十三岁‘ ELSE stu_age END stu_age, stu_sex FROM student;
结果如下:
更加详细请见:https://www.cnblogs.com/vincentbnu/p/9495609.html
原文:https://www.cnblogs.com/superdrew/p/11279631.html