日期:2014-05-17  浏览次数:20446 次

求一条优化语句
假设有abcde五个地区,都有一个共同的客户张三,我现在要统计业绩,除了a地区可以把张三的销售算进业绩中去,其他地区对应销售的业绩都不能包含张三。
我能想到的语句是
select * from table where 地区='a'
union all
select * from table where 地区 in('b','c','d','e') and 客户<>'张三'

用union all会不会使查询效率降低?因为有的语句还要使用group by的。除了这种写法,还有没有更好的语句,比如能否用case之类的?


------解决方案--------------------
引用:
能否用case when 地区='a' …… 这样类似的条件去判断所查询的结果?


可以的,不过这样和上面的union all 也是区别不大,可能性能还没有union all好。

select * from table 
where 1=case when 地区 in('b','c','d','e') and 客户<>'张三'
                  then 1
             when 地区 = 'a'
                  then 1
             else 0 
         end

------解决方案--------------------
引用:
能否用case when 地区='a' …… 这样类似的条件去判断所查询的结果?
case when是在select中对数据进行筛选,本身减少不了数据量。如果数据量能够控制,group by,union all这些甚至order by也不会带来什么性能问题