SQL语句中,如何使用含有if....else...判断语句

在我们开发中,有时要对数据库中的数据按照条件进行查询,用到if else类似的语句进行判断,那么if else语句只有在存储过程,触发器之类的才有,但是要在sql上当满足某种条件上要取不同的字段值,刚开始我还不会,最后查了资料,发现使用case when语句就可以解决,而且各种数据库都支持。

语法:

case when 条件1 then 结果1 when 条件2 then 结果2 else 结果N end

可以有任意多个条件,如果没有默认的结果,最后的else也可以不写,

select case when col1 > 1 then col2 else col3 end from XXXtable

一、[基本查询语句展示优化]


Sql代码 

#根据type查询  
SELECT id,title,type FROM table WHERE type=1;  
SELECT id,title,type FROM table WHERE type=2;  


 用if优化Sql代码 

#if(expr,true,false)  
SELECT id,title,type,if(type=1,1,0) as type1,if(type=2,1,0) as type2 FROM table;  
SELECT id,title,type,if(type=1,1,0) as type1,if(type=2,1,0) as type2 FROM table;  

 用case when优化Sql代码 

#case...when...then...when...then...else...end  
SELECT id,title,type,case type WHEN 1 THEN 'type1' WHEN 2 THEN 'type2' ELSE 'type error' END as newType FROM table;  


二、[统计数据性能优化]


Sql代码 

#两次查询不同条件下的数量  
SELECT count(id) AS size FROM table WHERE type=1  
SELECT count(id) AS size FROM table WHERE type=2  


 用if优化Sql代码 

#sum方法  
SELECT sum(if(type=1, 1, 0)) as type1, sum(if(type=2, 1, 0)) as type2 FROM table  
#count方法  
SELECT count(if(type=1, 1, NULL)) as type1, count(if(type=2, 1, NULL)) as type2 FROM table  
#亲测二者的时间差不多  
#建议用sum,因为一不注意,count就会统计了if的false中的0  


 用case when优化Sql代码 

#sum  
SELECT sum(case type WHEN 1 THEN 1 ELSE 0 END) as type1, sum(case type WHEN 2 THEN 1 ELSE 0 END) as type2 FROM table  
#count  
SELECT count(case type WHEN 1 THEN 1 ELSE NULL END) as type1, count(case type WHEN 2 THEN 1 ELSE NULL END) as type2 FROM table  

猜你喜欢

转载自www.cnblogs.com/dreaming317/p/12536893.html