这个查询我需要花费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
在我的解释中,它显示即时通讯使用临时;使用filesort
索引是:
活动表: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
非常感谢任何建议
非常感谢
答案 0 :(得分:2)
首先,试试这个:
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
我删除了一个不必要的子查询。同时删除ORDER BY
。我想你可以不进行排序,这必须加快查询速度。
我还删除了SQL_CALC_FOUND_ROWS
,因为正如我之前提到的,发出单独的COUNT(*)
查询应该更快。
答案 1 :(得分:0)
你的where子句在“a.Activity”上有一个“Or”。没有()围绕这两个活动,它会通过一切,所有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