改进这个非常慢的MySQL SELECT

时间:2012-10-05 10:43:56

标签: mysql indexing

我有这个非常慢的MySQL查询,我认为因为所有的JOIN(看起来很复杂,但这是很多表的问题):

SELECT DISTINCT doctors.doc_id, 
    doctors.doc_user, 
    doctors.doc_first, 
    doctors.doc_last, 
    doctors.doc_email, 
    doctors.doc_notes, 
    titles.tit_name, 
    specializations.spe_name, 
    activities.act_name, 
    users.use_first, 
    users.use_last,
    (SELECT COUNT(*) FROM locations WHERE locations.loc_doctor = doctors.doc_id) AS loc_count,
    (SELECT COUNT(*) FROM reception WHERE reception.rec_doctor = doctors.doc_id) AS rec_count,
    (SELECT COUNT(*) FROM visits INNER JOIN reports ON visits.vis_report = reports.rep_id  WHERE visits.vis_doctor = doctors.doc_id AND reports.rep_user LIKE '%s') AS vis_count
FROM
    doctors
INNER JOIN titles ON titles.tit_id = doctors.doc_title
INNER JOIN specializations ON specializations.spe_id = doctors.doc_specialization
INNER JOIN activities ON activities.act_id = doctors.doc_activity
LEFT JOIN locations ON locations.loc_doctor = doctors.doc_id
INNER JOIN users ON doctors.doc_user = users.use_id
WHERE
    ((doctors.doc_last LIKE %s) OR (doctors.doc_first LIKE %s) OR (doctors.doc_email LIKE %s)) 
    AND doctors.doc_user LIKE %s 
    AND locations.loc_province LIKE %s 
    AND doctors.doc_specialization LIKE %s 
    AND doctors.doc_activity LIKE %s 
ORDER BY %s

所有%s都是sprintf()PHP函数中的参数
最值得注意的是......我没有MySQL的索引!我认为我可以加快添加一些索引的过程...但是什么和哪里?有这么多的连接和搜索参数,我很困惑什么是有效的: - )

请帮忙吗? 提前谢谢!

2 个答案:

答案 0 :(得分:0)

您可以从在where条件中使用的那些列添加索引开始。

此外,您应该索引在连接中使用的那些字段,即主键和外键列。

我建议逐步尝试这些索引会产生真正的性能提升。

此外,我发现您在单个查询中获取了太多数据。如果确实不需要,请在不同的报告和页面中进行分解(如果可能),即使您进行了正确的索引,解决方案也不会具有很大的可扩展性,并且可能无法处理大量数据。

注意:您可能必须在通过'%'限定符查询的字段上创建全文索引。(即使用LIKE运算符)

答案 1 :(得分:0)

就像运营商一样慢。以下是应用索引和FULL TEXT的讨论

mysql like performance boost