企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
流程控制函数 1、case (1)、`CASE value WHEN [compare_value] THEN result [WHEN [compare_value] THEN result ...] [ELSE result] END` 当value等于compare_value时,则返回result,否则返回else里的result,如果没有else子句则返回null ~~~ mysql> SELECT CASE 1 WHEN 1 THEN 'one' -> WHEN 2 THEN 'two' ELSE 'more' END; -> 'one' 示例:select case dept_id when 1 then 'education' when 2 then 'accounting' else 'more' end, id,name from teacher; ~~~ (2)、 `CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END` 当第一个condition满足时,则返回result,否则返回else里的result,如果没有else子句时则返回null ~~~ mysql> SELECT CASE WHEN 1>0 THEN 'true' ELSE 'false' END; -> 'true' mysql> SELECT CASE BINARY 'B' -> WHEN 'a' THEN 1 WHEN 'b' THEN 2 END; -> NULL 示例:select case when dept_id=1 then 'edu' when dept_id=4 then 'acc' end,id from teacher; ~~~ 2、is null/is not null ~~~ insert into teacher values(1,null,4); select * from teacher where name is null; select * from teacher where name is not null; ~~~ 3、IF(expr1,expr2,expr3) 当expr1为1/true时,则返回expr2,否则返回expr3 ~~~ select if(id<dept_id,'yes','no'),id,dept_id from teacher; mysql> SELECT IF(1>2,2,3); -> 3 mysql> SELECT IF(1<2,'yes','no'); -> 'yes' mysql> SELECT IF(STRCMP('test','test1'),'no','yes'); -> 'no‘ select if(strcmp('id','dept_id') from teacher; ~~~ STRCMP 比较两个字符串,如果这两个字符串相等返回0,如果第一个参数是根据当前的排序小于第二个参数顺序返回-1,否则返回1。 4、IFNULL(expr1,expr2) 当expr1为非null时,则返回expr1,否则返回expr2 ~~~ mysql> SELECT IFNULL(1,0); -> 1 mysql> SELECT IFNULL(NULL,10); -> 10 mysql> SELECT IFNULL(1/0,10); -> 10 mysql> SELECT IFNULL(1/0,'yes'); -> 'yes' ~~~ 5、 NULLIF(expr1,expr2) 当expr1等于expr2时,则返回null,否则返回expr1 ~~~ mysql> SELECT NULLIF(1,1); -> NULL mysql> SELECT NULLIF(1,2); -> 1 ~~~