使用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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值