复合索引顺序MySQL查询
我正在尝试优化以下mysql查询。它运行约2.5秒。我已经读过关于复合索引的书,但我希望有人能帮助我理解如何使用这样的查询来排序复合索引,这些查询包含多个连接、许多where条件(包括日期范围)、group by和ORDER by(基于计算值)。我是否缺少一个有用的复合索引?是否有更有效的方法从这些表中提取数据?非常感谢您的帮助复合索引顺序MySQL查询,mysql,indexing,subquery,query-optimization,Mysql,Indexing,Subquery,Query Optimization,我正在尝试优化以下mysql查询。它运行约2.5秒。我已经读过关于复合索引的书,但我希望有人能帮助我理解如何使用这样的查询来排序复合索引,这些查询包含多个连接、许多where条件(包括日期范围)、group by和ORDER by(基于计算值)。我是否缺少一个有用的复合索引?是否有更有效的方法从这些表中提取数据?非常感谢您的帮助 SELECT branch.name AS branch, SUM(appointment.status = 'completed') AS `Completed`
SELECT
branch.name AS branch,
SUM(appointment.status = 'completed') AS `Completed`,
SUM(appointment.status = 'cancelled') AS `Cancelled`,
SUM(appointment.status = 'not completed') AS `Not Completed`,
SUM(appointment.status != 'rescheduled') AS `Total`
FROM rep
JOIN customer ON rep.id = customer.rep_id
JOIN office ON rep.office_id = office.id
JOIN appointment ON customer.id = appointment.customer_id
JOIN branch ON office.branch_id = branch.id
WHERE rep.active= 1
AND rep.group IN (1,2,3)
AND rep.deleted = 0
AND customer.saved = 0
AND (customer.rep_id != appointment.closed_by OR appointment.closed_by IS NULL)
AND customer.rep_id != 0
AND customer.deleted = 0
AND office.visible = 1
AND office.deleted = 0
AND appointment.date >= '2016-12-01'
AND appointment.date < '2017-11-30'
AND appointment.current = 1
GROUP BY branch.id
ORDER BY Completed
建议
根据条件删除周围不可用的()
LEFT JOIN customer ON rep.id = customer.rep_id
LEFT JOIN office ON rep.office_id = office.id
LEFT JOIN appointment ON customer.id = appointment.customer_id
LEFT JOIN branch ON office.branch_id = branch.id
在不了解任何数据的情况下,您的查询建议使用索引
office(已删除、可见、分支机构id)
。然而,这个表似乎只包含少数行,因此这个索引可能不会有多大帮助;要选择更好的策略,可以尝试识别强过滤器。例如,如果99%的数据将具有customer.saved=1
或约会.current!=1
,您可以尝试使用此选项优化查询,但这取决于您的数据。此外,为了清楚起见,您应该用join
(如果office.branch\u id
为非空,则最后一个也应替换为左join
)
LEFT JOIN customer ON rep.id = customer.rep_id
LEFT JOIN office ON rep.office_id = office.id
LEFT JOIN appointment ON customer.id = appointment.customer_id
LEFT JOIN branch ON office.branch_id = branch.id