0

我的这个查询需要 45 秒才能执行。我对正在搜索的所有字段都有索引。

SELECT SQL_CALC_FOUND_ROWS g.app_group_id, g.id as g_id, p.`id` as form_id, 
       a.`user`   as activity_user,a.`activity` as app_act ,a.* 
FROM grouped g 
INNER JOIN 
(SELECT max(id) as id, app_group_id FROM grouped GROUP BY app_group_id) g1 
ON g1.app_group_id = g.app_group_id AND g.id = g1.id 
INNER JOIN form p 
on p.id = g.id 
    INNER JOIN 
    (SELECT a.id, a.date_time, a.user, a.activity FROM log a) a 
    ON g.id = a.id 
WHERE p.agname like '%blahblah%' and p.`save4later` != 'y' 
      and a.activity = 'APP       Submitted' or a.activity = 'InstaQUOTE' 
ORDER BY app_group_id DESC limit 0, 100

在我的解释中,它显示我正在使用临时使用;使用文件排序

索引是:

活动表:PRIMARY activity_id INDEX date_time INDEX id INDEX 活动 INDEX 用户

表格:PRIMARY id INDEX id_md5 INDEX dateadd INDEX dateu INDEX agent_or_underwriter INDEX

分组表:UNIQUE id INDEX app_group_id INDEX agent_or_underwriter save4later

非常感谢任何建议

非常感谢

4

2 回答 2

2

To start with, try this one:

SELECT
  g.app_group_id,
  g.id AS g_id,
  p.id AS form_id,
  a.user AS activity_user,
  a.activity AS app_act,
  a.id,
  a.date_time
FROM grouped g 
INNER JOIN 
  (SELECT MAX(id) AS id, app_group_id FROM grouped GROUP BY app_group_id) g1 
  ON g1.app_group_id = g.app_group_id AND g.id = g1.id 
INNER JOIN form p 
  ON p.id = g.id 
INNER JOIN log a 
  ON g.id = a.id 
WHERE p.agname LIKE '%blahblah%'
  AND p.save4later != 'y'
  AND a.activity IN('APP       Submitted', 'InstaQUOTE')
LIMIT 0, 100

I removed an unnecessary subquery. Also removed ORDER BY. I guess you could do without sorting, and that must speed the query up a lot.

I also removed SQL_CALC_FOUND_ROWS, because, as I mentioned earlier, it should be faster to issue a separate COUNT(*) query.

于 2012-04-19T15:19:13.347 回答
0

您的 where 子句在“a.Activity”上有一个“或”。如果没有 ( ) 围绕这两个活动,它会经历一切,所有 P、G、G1 别名。我猜这可能是你更大的问题。

此外,我会确保您在“表单”表上有一个索引,其中 ( Save4Later ) 列已编入索引

我会像这样更新查询:

SELECT STRAIGHT_JOIN SQL_CALC_FOUND_ROWS 
      g.app_group_id, 
      g.id as g_id, 
      QualifyPages.Form_id, 
      a.`user` as activity_user,
      a.`activity` as app_act,
      a.* 
   FROM
      ( select p.ID as Form_ID
           from  FORM p
           WHERE p.`save4later` != 'y' 
             AND p.agname like '%blahblah%' ) QualifyPages

         JOIN Grouped g
            on QualifyPages.Form_ID = g.ID

            INNER JOIN 
            ( SELECT app_group_id,
                     max(id) as MaxIDPerGroup
                 FROM 
                    grouped 
                 GROUP BY 
                    app_group_id ) g1 
             ON g.app_group_id = g1.app_group_id
            AND g.id = g1.MaxIDPerGroup 

           INNER JOIN 
            ( SELECT a.id, a.date_time, a.user, a.activity 
                 FROM log a
                 WHERE a.activity = 'APP       Submitted' 
                    or a.activity = 'InstaQUOTE' ) a 
               ON g.id = a.id 
   ORDER BY 
      g.app_group_id DESC 
   limit 
      0, 100
于 2012-04-19T15:36:17.537 回答