查询会在分组时永远挂起

时间:2013-09-27 08:16:08

标签: mysql

我们无法让这个简单的查询工作:

SELECT * FROM
(SELECT  h.*, h.NewValue AS STATUS,
         (SELECT h2.CreatedDate
          FROM siebel_service_request_history h2
          WHERE h2.Field = 'Status' AND h2.CreatedDate > h.CreatedDate AND
                h2.SiebelID = h.SiebelID
          ORDER BY h2.CreatedDate
          LIMIT 1
         ) AS nextCreatedDate
  FROM siebel_service_request_history h WHERE h.Field ='Status') h

  GROUP BY h.SiebelID, h.Status

通过SiebelID进行分组(但速度很慢)可以正常运行,如果我们按Status添加分组,它会永远挂起。但是我们需要分组中包含的两个字段才能获得我们想要的数据。

我们有完全相同的查询在salesforce_case_history表中运行和工作(它运行得非常快,确切地说,我们在两个表中的记录数大致相同(salesforce_case_history - - 1159870记录VS siebel_service_request_history - 1202865条记录)):

SELECT * FROM (SELECT h.*, h.NewValue AS STATUS,
         (SELECT h2.CreatedDate
          FROM salesforce_case_history h2
          WHERE h2.Field = 'Status' AND h2.CreatedDate > h.CreatedDate AND
                h2.CaseId = h.CaseId
          ORDER BY h2.CreatedDate
          LIMIT 1
         ) AS nextCreatedDate
  FROM salesforce_case_history h WHERE h.Field ='Status'
 ) h
GROUP BY h.CaseId, h.Status

我们还在siebel_service_request_history上为内部子选择搜索创建了相同的复合索引,包括我们创建的三个字段(SiebelIDCreatedDateField)表salesforce_case_history。我们尝试了几乎所有我们知道的东西,但不幸的是没有提出这个问题的根本问题。

1 个答案:

答案 0 :(得分:0)

尝试:

SELECT  h.*, h.NewValue AS STATUS,
         (SELECT h2.CreatedDate
          FROM siebel_service_request_history h2
          WHERE h2.Field = 'Status' AND h2.CreatedDate > h.CreatedDate AND
                h2.SiebelID = h.SiebelID
          ORDER BY h2.CreatedDate
          LIMIT 1
         ) AS nextCreatedDate
  FROM siebel_service_request_history h WHERE h.Field ='Status'

  GROUP BY h.SiebelID, h.Status

你有一个额外的不必要的子查询步骤。

还尝试从子查询创建表,在您分组的内容上添加索引,然后将select * from table分组。将大大加快,我在我的所有例程中使用带索引的临时表。