需要有关加快查询的建议

时间:2011-04-19 18:33:00

标签: mysql sql join

此查询大约需要9秒钟,并返回2条记录。

SELECT

s.description, s.improvement,
s.first_name, s.last_name, s.finding, s.action, s.share, 
s.learned, s.timestamp, d.title as department_title, 
group_concat(DISTINCT g.title SEPARATOR " | ") as strategic_goals,
group_concat(DISTINCT m.statement SEPARATOR " | ") as mission_references,
group_concat(DISTINCT meas.statement SEPARATOR " | ") as measure_statement,
group_concat(DISTINCT o.statement SEPARATOR " | ") as outcome_statement,
group_concat(DISTINCT i.title SEPARATOR " | ") as ilo_title,
group_concat(DISTINCT cv.title SEPARATOR " | ") as core_value_title,
y1.year as current_year_title, y2.year as previous_year_title,
u.file_name as file_name

FROM summary s

LEFT JOIN year y1 ON s.current_year_id = y1.id
INNER JOIN year y2 ON s.previous_year_id = y2.id

INNER JOIN strategic_goal_entries sge ON s.id = sge.summary_id
INNER JOIN goal g ON sge.goal_id = g.id

INNER JOIN outcome o ON s.id = o.summary_id
LEFT JOIN measure meas ON o.id = meas.outcome_id

INNER JOIN department d ON s.department_id = d.id
LEFT JOIN uploads u ON s.id = u.summary_id 

INNER JOIN mission_entries me ON s.id = me.summary_id
LEFT JOIN mission m ON me.mission_id = m.id

LEFT JOIN ilo_entries ie ON s.id = ie.summary_id
LEFT JOIN ilo i ON ie.ilo_id = i.id

INNER JOIN core_value_entries cve ON s.id = cve.summary_id
INNER JOIN core_value cv ON cve.core_value_id = cv.id

INNER JOIN executive_of_department eod ON s.department_id = eod.department_id

WHERE eod.executive_id = 3

GROUP BY s.id

我添加了其余的主键。查询从9秒到2秒。

然后我将引用其他表的主键的字段设置为索引字段。查询从2秒到20秒,我分配了太多索引吗?

有什么方法可以加快这个速度?

1 个答案:

答案 0 :(得分:1)

1。设置索引等后,您可以通过限制JOIN条件来加快速度。例如,而不是

LEFT JOIN uploads u ON s.id = u.summary_i

DO

LEFT JOIN uploads u ON (s.id = u.summary_i AND s.id = 3)

在所有表已加入后, 评估WHERE子句。尽可能预先确定JOIN条件。


2。您是否尝试从您的选择中构建视图并执行SELECT * FROM myView WHERE myView.id = 3

更新:阅读this blog comment