帮助加速嵌套选择查询

时间:2011-09-14 16:29:33

标签: mysql sql

我有以下选择查询我执行,但是对于甚至~6000条记录来说它是惊人的慢,如果有另一种方法来构建查询,我很好奇吗?

select sum(Q.R) 
from (select 
        T.drawing_no,
        max(T.drawing_rev),
        T.R 
      from (select 
              drawing_no,
              drawing_rev,
              sum(price_total) as R 
            from data_pipe_drawing 
            where drawing_status="IP" 
            group by 
              drawing_no,
              drawing_rev) as T 
      group by T.drawing_no) as Q

在英语中,查询查找状态为IP的所有图纸,通过drawing_no + drawing_rev汇总价格(price_total),然后仅返回每个图纸的最高版本的price_total,并将其全部滚动以获得高价格_total

因此,如果查询成立,则在达到max(T.drawing_rev)之前:

 Drawing A Rev 1 Total Cost $100
 Drawing A Rev 0 Total Cost $50
 Drawing B Rev 0 Total Cost $200

绘图A Rev 0从总计中删除。总计300美元。

希望这有意义......感谢任何建议!

2 个答案:

答案 0 :(得分:1)

根据我的评论,我对您编写的查询感到不安全,我会对相关的子查询做一些事情,比如这样......

  SELECT
--  drawing_no,
    SUM(price_total)
  FROM
    data_pipe_drawing AS data
  WHERE
    drawing_status="IP" 
    AND drawing_rev = (SELECT MAX(drawing_rev) FROM data_pipe_drawing WHERE drawing_status = "IP" AND drawing_no = data.drawing_no)
--GROUP BY
--  drawing_no

-- Commented lines useful for testing individual drawings

然后在(drawing_status, drawing_no, drawing_rev)

上有一个索引


或者甚至可能......

  SELECT
    SUM(data.price_total)
  FROM
    data_pipe_drawing AS data
  INNER JOIN
  (
    SELECT
      drawing_status,
      drawing_no,
      MAX(drawing_rev) AS drawing_rev
    FROM
      data_pipe_drawing
    GROUP BY
      drawing_status,
      drawing_no
  )
    AS lookup
      ON  lookup.drawing_number = data.drawing_number
      AND lookup.drawing_rev    = data.drawing_rev
      AND lookup.drawing_status = data.drawing_status
  WHERE
    data.drawing_status="IP" 

修改

将基于JOIN的解决方案更改为可能对多个绘图状态更友好,等待来自OP。

答案 1 :(得分:0)

尝试使用临时表

分隔您的查询
create temporary table tmp_table select 
              drawing_no,
              drawing_rev,
              sum(price_total) as R 
            from data_pipe_drawing 
            where drawing_status="IP" 
            group by 
              drawing_no,
              drawing_rev;

select sum(Q.R) 
from (select 
        T.drawing_no,
        max(T.drawing_rev),
        T.R 
      from tmp_table T 
      group by T.drawing_no) as Q