流程函数是非常关键的一类函数,通过他们可以实现在一个SQL语句中做条件选择,提高语言的效率。先来看下练习用到数据集:
mysql> select * from salary;
+--------+---------+
| userid | salary |
+--------+---------+
| 1 | 1000.00 |
| 2 | 2000.00 |
| 3 | 3000.00 |
| 4 | 4000.00 |
| 5 | 5000.00 |
| 1 | NULL |
+--------+---------+
6 rows in set (0.01 sec)
if(value,t,f)
value=1 执行 t(true) 反之执行 f(false) :
mysql> select if(salary>2000,'high','low') from salary;
+------------------------------+
| if(salary>2000,'high','low') |
+------------------------------+
| low |
| low |
| high |
| high |
| high |
| low |
+------------------------------+
6 rows in set (0.01 sec)
ifnull(value1,value2)
类似于 py 中的 fillna:
mysql> select ifnull(salary,0) from salary;
+------------------+
| ifnull(salary,0) |
+------------------+
| 1000.00 |
| 2000.00 |
| 3000.00 |
| 4000.00 |
| 5000.00 |
| 0.00 |
+------------------+
6 rows in set (0.00 sec)
case when [value] then [result] else [default] end
很难说这只是一个函数,更像是一块条件判断语句写成一行,易读性上有待商榷:
mysql> select case when salary<=2000 then 'low' else 'high' end from salary;
+---------------------------------------------------+
| case when salary<=2000 then 'low' else 'high' end |
+---------------------------------------------------+
| low |
| low |
| high |
| high |
| high |
| high |
+---------------------------------------------------+
6 rows in set (0.00 sec)
这里看到由于 null<=2000 为null,故归为else 结果输出成了high,这也是实现没有对数据做预处理的后果。
另外,when [value1] then [result1]
是可以进行多种枚举的,并不像 py 那样 if ... else ... elseif ...