1.Mysql的if作为表达式用

IF(expr1,expr2,expr3)

含义:如果 expr1 是TRUE (expr1 <> 0 and expr1 <> NULL),则 IF()的返回值为expr2; 否则返回值则为 expr3。

mysql> select *,if(sex=1,"男","女") as new_sex  from student where sex != "";
+----+------+--------+---------+
| id | sex  | name   | new_sex |
+----+------+--------+---------+
|  1 |    1 | 张三   ||
|  2 |    2 | 翠花   ||
|  3 |    1 | 李四   ||
+----+------+--------+---------+
3 rows in set (0.00 sec)

备注:当翠花的性别为0时,即便 sex != “”,也查询不出来;不知何故;

等同于

mysql> select *, CASE sex WHEN 1 THEN '男' ELSE '女' END as new_sex from student where sex != '';
+----+------+--------+---------+
| id | sex  | name   | new_sex |
+----+------+--------+---------+
|  1 |    1 | 张三   ||
|  2 |    2 | 翠花   ||
|  3 |    1 | 李四   ||
+----+------+--------+---------+
3 rows in set (0.00 sec)

2.存储过程中作为流程控制语句使用

IF ELSE 做为流程控制语句使用

IF search_condition THEN 
    statement_list  
[ELSEIF search_condition THEN]  
    statement_list ...  
[ELSE 
    statement_list]  
END IF 

备注:了解即可;

3.实战

1.需求:有这样一个表,需要求出第一列大于3的个数,第二列大于3的个数;

表信息如下:

mysql> select * from data;
+-----------+-----------+
| data_co_1 | data_co_2 |
+-----------+-----------+
|      1.00 |      0.50 |
|      0.90 |      1.50 |
|      3.00 |      0.70 |
|      4.00 |      3.00 |
|      0.01 |     80.00 |
|    100.00 |      0.92 |
|      0.70 |      0.25 |
+-----------+-----------+
7 rows in set (0.00 sec)

2.方案1 ,使用sum(if()) ;

mysql> select sum(if (data_co_1 > 3,1,0)) count1,sum(if (data_co_2 > 3,1,0)) count2 from data;
+--------+--------+
| count1 | count2 |
+--------+--------+
|      2 |      1 |
+--------+--------+
1 row in set (0.00 sec)

2.2.方案2 ,使用sum(case when) ;

mysql> select sum(case when data_co_1 >3 then 1 else 0 end) count1,sum(case when data_co_2 >3 then 1 else 0 end) count2 from data;
+--------+--------+
| count1 | count2 |
+--------+--------+
|      2 |      1 |
+--------+--------+
1 row in set (0.00 sec)
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐