使SQL查询更有效

时间:2011-01-23 14:47:40

标签: sql mysql postgresql

如何提高此SQL查询的效率?

SELECT 
  (SELECT COUNT(*) FROM table WHERE price < 10) AS priceUnder10,
  (SELECT COUNT(*) FROM table WHERE price BETWEEN 10 AND 20) AS price10to20,
  (SELECT COUNT(*) FROM table WHERE price > 20) AS priceOver20,
  (SELECT COUNT(*) FROM table WHERE colour = 'Red') AS colourRed,
  (SELECT COUNT(*) FROM table WHERE colour = 'Green') AS colourGreen,
  (SELECT COUNT(*) FROM table WHERE colour = 'Blue') AS colourBlue;

我已经在pricecolour列上添加了索引,因此我正在寻找一种更好的方法来聚合数据。

我已经研究过使用GROUP BYHAVING,自联接和窗口函数,但无法弄清楚如何实现相同的结果。

任何建议都非常感谢。

3 个答案:

答案 0 :(得分:8)

SELECT 
       COUNT(CASE WHEN price < 10 THEN 1 END) AS priceUnder10,
       COUNT(CASE WHEN price BETWEEN 10 AND 20 THEN 1 END) AS price10to20,
       COUNT(CASE WHEN price> 20 THEN 1 END) AS priceOver20,
       COUNT(CASE WHEN colour = 'Red' THEN 1 END) AS colourRed,
       COUNT(CASE WHEN colour = 'Green' THEN 1 END) AS colourGreen,
       COUNT(CASE WHEN colour = 'Blue' THEN 1 END) AS colourBlue
from YourTable  
WHERE price IS NOT NULL OR  colour IN ('Red','Green','Blue' )

答案 1 :(得分:2)

根据数据库处理布尔表达式的方式,这个:

select sum(price<10),sum(price between 10 and 20)...  from tab; 

或者

select sum(case when price<10 then 1 else 0 end),sum(case when price between 10 and 20 then 1 else 0 end)...  from tab; 

可能有帮助。

答案 2 :(得分:0)

SELECT count(*) as products, 

if(price < 10, 'price band 1',
 if (price between 10 and 20, 'price band 2',
  'price band 3'
 )
) as priceband,
  t.colour

from table t
group by t.colour, pricebrand

那会给你

products    colour    priceband
53          red       price band 1
65          red       price band 2
12          blue      price band 1
23          blue      price band 2