日期:2014-05-16  浏览次数:20754 次

这样一个sql语句,该如何优化呢?谢谢~~~解决立刻给分
SELECT  
(SELECT   COUNT(*)   FROM   table1   WHERE   id1=1001)   AS   a1,
(SELECT   COUNT(*)   FROM   table1   WHERE   id2=2001)   AS   a2,
(SELECT   COUNT(*)   FROM   table1   WHERE   id1=1001   AND   id2=2001)   AS   a3,
(SELECT   SUM(num1)   FROM   table1   WHERE   id1=1001)   AS   b1,
(SELECT   SUM(num1)   FROM   table1   WHERE   id2=2001)   AS   b2,
(SELECT   SUM(num1)   FROM   table1   WHERE   id1=1001   AND   id2=2001)   AS   b3,
(SELECT   SUM(num2)   FROM   table1   WHERE   id1=1001)   AS   c1,
(SELECT   SUM(num2)   FROM   table1   WHERE   id2=2001)   AS   c2,
(SELECT   SUM(num2)   FROM   table1   WHERE   id1=1001   AND   id2=2001)   AS   c3

这样就可以获得a1,a2,a3,b1,b2,b3,c1,c2,c3这9个值,有什么方法可以把这个sql语句进行优化么?就是让速度再快一些




------解决方案--------------------
给ID1和ID2建上索引。
------解决方案--------------------
呵呵,建立索引可以的

ps,有必要这样写sql嘛?可能对于写程序来讲可以只用写一次sql就把数据都读出来吧.个人觉得不好
------解决方案--------------------
首先sql语句优化如下,目的减少扫描次数。
SELECT
(SELECT COUNT(*) as a1, sum(num1) as b1, sum(num2) as c1 FROM table1 WHERE id1=1001)
(SELECT COUNT(*) as a2, sum(num1) as b2, sum(num2) as c2 FROM table1 WHERE id2=2001)
(SELECT COUNT(*) as a3, sum(num1) as b3, sum(num2) as c3 FROM table1 WHERE id1=1001 AND id2=2001) AS c3)
)
并且在表的id1, id2建立符合簇索引就可以了。