SQL语句中,如何使⽤含有if....判断语句
在我们开发中,有时要对数据库中的数据按照条件进⾏查询,⽤到if else类似的语句进⾏判断,那么if else语句只有在存储过程,触发器之类的才有,但是要在sql上当满⾜某种条件上要取不同的字段值,刚开始我还不会,最后查了资料,发现使⽤case when语句就可以解决,⽽且各种数据库都⽀持。
语法:
case when条件1 then结果1 when条件2 then结果2 else结果N end
可以有任意多个条件,如果没有默认的结果,最后的else也可以不写,
select case when col1 >1then col2 else col3 end from XXXtable
⼀、[基本查询语句展⽰优化]
Sql代码
#根据type查询
SELECT id,title,type FROM table WHERE type=1;
sql触发器的使用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代码
#d
SELECT id,title,type,case type WHEN1THEN'type1'WHEN2THEN'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 WHEN1THEN1ELSE0END) as type1, sum(case type WHEN2THEN1ELSE0END) as type2 FROM table
#count
SELECT count(case type WHEN1THEN1ELSE NULL END) as type1, count(case type WHEN2THEN1ELSE NULL END) as type2 FROM table
获取更多精彩内容,学习资料,视频等,请关注【程序员Style】,回复关键字即可。