我有一个SQL查询,可从多个表中提取数据。我唯一遇到的问题实际上是查询花费了很长时间,我想知道是否仍然可以加快查询速度。我通过使用INNER JOIN而不是LEFT JOIN进行了一些小的改进,但是查询速度很慢。
SELECT
clientlist.CRMContactId,
clientlist.ClientAdviser,
COALESCE(NULLIF(clientlist.FirstName, ""), clientlist.CorporateName) AS FirstName,
clientlist.LastName,
clientlist.ServiceStatusName,
FORMAT(t.totalfum, 2) AS "Funds Under Management",
FORMAT(d.totalfci, 2) AS "Total Income",
(SELECT DueDate
FROM tasks
WHERE ClientRef = clientlist.ClientRef
AND `Status` <> "Complete"
ORDER BY DueDate DESC
LIMIT 1) AS NextDate,
(SELECT CompletedDate
FROM tasks
WHERE ClientRef = clientlist.ClientRef
AND `Status` = "Complete"
ORDER BY DueDate DESC
LIMIT 1) AS LastDate
FROM
clientlist
INNER JOIN
(SELECT
plans.ClientId, SUM(plans.CurrentVal) AS totalfum
FROM
plans
GROUP BY
plans.ClientId) t ON clientlist.CRMContactId = t.ClientId
INNER JOIN
(SELECT
adviserfci.ClientId, SUM(adviserfci.Payable) AS totalfci
FROM
adviserfci
WHERE
IncomeType IN ("Renewal Commission", "Ongoing Fee", "Fund Based Commission")
OR (Incometype = "Payaway Received"
AND UnderlyingIncomeType IN ("Renewal", "Ongoing Fee", "Fund Based"))
GROUP BY
adviserfci.ClientId) d ON clientlist.CRMContactId = d.ClientId
WHERE
d.totalfci IS NOT NULL
我还在某处阅读了explain命令,它将帮助您确定问题,但是我不理解响应。
有什么办法可以提高此查询的性能?
答案 0 :(得分:0)
首先要为这些表创建索引吗?
不知道您的数据结构和要放入哪种查询负载很难说,但是乍一看,我想说这些索引应该提高性能,如果还没有的话:
如果您尚未设置表主键,并且从列名称中听起来像是不错的候选键,那么如果可行,您可以用一块石头杀死两只鸟。
答案 1 :(得分:0)
将d.totalfci IS NOT NULL
的测试折叠到生成它的子查询中,即使它需要放在HAVING
子句中。
添加一些索引
tasks: INDEX(ClientRef, `Status`, DueDate)
plans: INDEX(ClientId, CurrentVal)
adviserfci: INDEX(ClientId)