4个查询在同一个表上,更好的方法?

时间:2010-08-12 01:18:12

标签: sql mysql query-optimization

目前我正在做一个查询,有3个子查询,
所有查询都在同一张桌子上,
所有查询都有不同的where子句

我已经考虑过做一个小组然而这会破坏SUM()

这是查询

SELECT SUM(club) AS club, 
(SELECT COUNT(id) FROM action_6_members WHERE SUBSTR(CODE, 1, 1) = '9') AS 5pts,
(SELECT COUNT(id) FROM action_6_members WHERE SUBSTR(CODE, 1, 1) = 'A') AS 10pts,
(SELECT COUNT(id) FROM action_6_members WHERE SUBSTR(CODE, 1, 1) NOT IN('9', 'A')) AS General
FROM action_6_members;

这里是解释

id  select_type  table             type  rows  Extra        
1   PRIMARY      action_6_members  ALL   1471               
4   SUBQUERY     action_6_members  ALL   1471  Using where  
3   SUBQUERY     action_6_members  ALL   1471  Using where  
2   SUBQUERY     action_6_members  ALL   1471  Using where  

2 个答案:

答案 0 :(得分:3)

使用:

SELECT SUM(club) AS club, 
       SUM(CASE WHEN SUBSTR(CODE, 1, 1) = '9' THEN 1 ELSE 0 END) AS 5pts,
       SUM(CASE WHEN SUBSTR(CODE, 1, 1) = 'A' THEN 1 ELSE 0 END) AS 10pts,
       SUM(CASE WHEN SUBSTR(CODE, 1, 1) NOT IN('9', 'A') THEN 1 ELSE 0 END) AS General
  FROM action_6_members;

答案 1 :(得分:0)

调整一下:

SELECT SUM(club) as club, COUNT(1) FROM action_6_members GROUP BY SUBSTR(CODE, 1, 1)