首页 > mysql > 在sql语句中使用流程控制

在sql语句中使用流程控制

作者:bin
目录
[隐藏]

一、if语句

这里使用这个数据表(t11)做示范

 +--------+---------+
 | userid | salary |
 +--------+---------+
 | 1 | 1000.00 |
 | 2 | 2000.00 |
 | 3 | 3000.00 |
 | 4 | 4000.00 |
 | 5 | 9000.00 |
 +--------+---------+

if (condition, true, false)

如果condition 成立,返回true位置的值,反之返回false位置的值,示例:

select *,if(salary>2000,"有钱人","穷人") from t11;

ifnull(var, true)

如果var为null,就返回true位置的值,反之返回var值

 select *,ifnull(salary,0) from t11;

二、case语句

case condition then true else false end

如果condition成立返回true位置的值,反之返回false位置的值,示例如下:

应用场景:
表中有4个字段,满足任意2个字段为1的数据有哪些;

select *  from t12 where 1=1 
and (
 case when a1= 1 then 1 else 0 end  
+case when a2= 1 then 1 else 0 end  
+case when a3= 1 then 1 else 0 end  
+case when a4= 1 then 1 else 0 end 
) = 2 ;

这里使用if

三、循环REPEAT

这里演示一个简单的repeat,until后返condition,这里为0即只执行一次

repeat
select "hello world"
until 0 end repeat

四、循环WHILE

使用方法while condition do code  end while,示例如下:

set @a=0;
while @a<10 do
set @a=@a+1;
end while;

您必须 [ 登录 ] 才能发表留言!