mysql中if()、ifnull()、nullif()、isnull()函数
if()
if(expr1,expr2,expr3):
如果expr1的值为true,则返回expr2的值,如果expr1的值为false,则返回expr3的值。类似三目运算符
ifnull()
ifnull(expr1,expr2):
如果expr1的值为null,则返回expr2的值,如果expr1的值不为null,则返回expr1的值。
nullif()
nullif(expr1,expr2):
如果expr1=expr2成立,那么返回值为null,否则返回值为expr1的值。
select nullif('a','a'); -- 输出结果:null select nullif('a','b'); -- 输出结果:a
isnull()
isnull(expr):
如果expr的值为null,则返回1,如果expr1的值不为null,则返回0。
select isnull(null); -- 输出结果:1 select isnull('hello'); -- 输出结果:0
instr()
instr函数为字符查找函数,其功能是查找一个字符串在另一个字符串中首次出现的位置。
在此函数中可以自定义查找的初始位置,与出现次数的位置。
在一些特定的sql查询中可以替换like进行模糊查询,可以代替in判断包含关系
- 在abcd中查找a的位置,从第一个字母开始查,查找第一次出现时的位置
select instr(‘abcd','a',1,1) from dual; —1 select instr(‘abcd','c',1,1) from dual; —3 select instr(‘abcd','e',1,1) from dual; —0
- 应用于模糊查询:instr(字段名/列名, ‘查找字段’)
select code,name,dept,occupation from staff where instr(code, ‘001')> 0;
- 等同于
select code, name, dept, occupation from staff where code like ‘%001%' ;
- 应用于判断包含关系:
select ccn,mas_loc from mas_loc where instr(‘fh,fhh,fhm',ccn)>0;
- 等同于
select ccn,mas_loc from mas_loc where ccn in (‘fh','fhh','fhm');
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论