事前准备:实例用的表结构和数据
/*
Navicat MySQL Data Transfer
Source Server : work
Source Server Version : 50616
Source Host : localhost:3306
Source Database : souvc
Target Server Type : MYSQL
Target Server Version : 50616
File Encoding : 65001
Date: 2018-03-08 18:19:18
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`state` tinyint(4) DEFAULT NULL,-- 1:有效;2:无效
`type` tinyint(4) DEFAULT NULL,-- 1:普通员工;2:中层员工;3:高层员工
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '张三', '1', '1');
INSERT INTO `user` VALUES ('2', '李四', '1', '2');
INSERT INTO `user` VALUES ('3', '王五', '2', '3');
INSERT INTO `user` VALUES ('4', '赵六', '2', '2');
CASE fieldname
WHEN value1 THEN result1
WHEN value2 THEN result2
WHEN value3 THEN result3
……
ELSE defaultresult
END
SELECT
`id` '用户ID',
`name` '用户名称',
(
CASE `state`
WHEN 1 THEN '正常'
WHEN 2 THEN '不正常'
ELSE NULL
END
) '用户状态'
FROM
`user`
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN condition3 THEN result3
……
ELSE defaultresult
END
SELECT
`id` '用户ID',
`name` '用户名称',
(
CASE
WHEN `state`=1 THEN '正常'
WHEN `state`=2 THEN '不正常'
ELSE NULL
END
) '用户状态'
FROM
`user`
IF(condition,result1,result2)
SELECT
`id` '用户ID',
`name` '用户名称',
IF(state=1,'正常','不正常') '用户状态'
FROM
`user`
ELT(condition,result1,result2,result3,...)
注意:condition的值必须是顺序1、2、3、...才会对应结果result1、result2、result3、...
SELECT
`id` '用户ID',
`name` '用户名称',
`type`,
ELT(type,'普通员工','中层员工','高层员工') '用户类型'
FROM
`user`;