IF 语句
格式: IF(condition, trueResult, falseResult)
示例1:
select id, name, if(gender='m', '男', if(gender='f', '女', '匿')) gender, age from user;
结果:
| id | name | gender| age |
+----+-----+-------+------+
| 1 | 张杉 | 男 | 25 |
| 2 | 李思 | 女 | 20 |
| 3 | 王伍 | 男 | 29 |
| 4 | 赵琉 | 女 | 18 |
| 5 | 钱颀 | 匿 | 21 |
示例2:
select id, name, if(gender is NULL,'匿', gender) gender, age from user;
结果:
| id | name | gender | age |
+----+--------+--------+------+
| 1 | 张杉 | m | 25 |
| 2 | 李思 | f | 20 |
| 3 | 王伍 | m | 29 |
| 4 | 赵琉 | f | 18 |
| 5 | 钱颀 | 匿 | 21 |
示例3:
select if(100%0 is null, -1, 0);
结果:
-1
IFNULL
格式: IFNULL( expr1, expr2)
含义: 若表达式expr1为NULL, 则返回expr2的值, 否则返回expr1的值
它其实是翻版的if语句,翻译后的if语句应该是:if(expr1 is null, expr2, expr1)
示例1:
select ifnull(1, 0); // 1
select ifnull(0, 1); // 0
select ifnull(100%0, 0); // 0
CASE - WHEN - THEN- END
格式: CASE field WHEN a THEN aResult WHEN b THEN bResult .... [ELSE otherResult] END
示例1:
select id, name, (case gender when 'm' then '男' when 'f' then '女' else '匿' end) gender, age from user;
结果:
| id | name | gender | age |
+----+--------+--------+------+
| 1 | 张杉 | 男 | 25 |
| 2 | 李思 | 女 | 20 |
| 3 | 王伍 | 男 | 29 |
| 4 | 赵琉 | 女 | 18 |
| 5 | 钱颀 | 匿 | 21 |
附1: 练习SQL语句
CREATE TABLE `user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`gender` varchar(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `user` (`id`, `name`, `gender`, `age`)
VALUES
(1,'张杉','m',25),
(2,'李思','f',20),
(3,'王伍','m',29),
(4,'赵琉','f',18),
(5,'钱颀',NULL,21);
附2:控制台输出中文乱码解决方案:
show variables like 'character_set%';
set character_set_client=utf8;
set character_set_connection=utf8;
set character_set_results=utf8
set character_set_server=utf8