以下查询的运行速度非常慢...
SELECT
CONCAT(users.first_name, ' ', users.last_name) AS user_name,
leads.first_name AS first_name,
comments.*,
FROM comments
INNER JOIN users ON
users.id = comments.user_id
INNER JOIN leads ON
leads.id = comments.lead_id AND
leads.company_id = 1
ORDER BY
`sort` DESC,
reply ASC,
id ASC
LIMIT 80,20
销售线索表具有约8000条记录 用户表有300条记录 评论表有约500,000条记录
我在Leads.id,comments.lead_id,leads.company_id,users.id和comments.user_id,comments.sort,comments.reply,comments.id上都有一个索引
有人可以解释如何优化此查询吗?
答案 0 :(得分:1)
将leads
移至from
列表的第一位:
SELECT
CONCAT(users.first_name, ' ', users.last_name) AS user_name,
leads.first_name AS first_name,
comments.*
FROM leads
INNER JOIN comments ON
comments.lead_id = leads.id
INNER JOIN users ON
users.id = comments.user_id
WHERE leads.company_id = 1
ORDER BY
`sort` DESC,
reply ASC,
id ASC
LIMIT 80,20
这允许leads(company)
上的索引在连接到其他表之前立即过滤出尽可能多的行。
效果应提高约1/(fraction of leads with company_id = 1)