使用if或case when优化SQL

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

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

 用if优化

#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优化

#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;

 

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

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

 用if优化

#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优化

#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

 亲测查询两次和优化后查询一次的时间一样,优化时间为1/2

 

你可能感兴趣的:(sql,case,when,if)