首页 > 数据库技术 > 详细

使用if或case when优化SQL

时间:2016-03-30 02:07:34      阅读:215      评论:0      收藏:0      [点我收藏+]

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

#根据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

?

使用if或case when优化SQL

原文:http://java--hhf.iteye.com/blog/2287260

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!