[英]mySql Query running super slow
我看過一些關於慢速查詢的帖子,但沒有一個得到我希望的答案。
我已經盯着這個查詢很久了,出於某種原因看不出是什么讓這個日期如此緩慢,比如 2022-01-01 > 2022-12-21 甚至需要 80 秒......
所以這是查詢
SELECT
accounts.first_name,
accounts.last_name,
accounts.email,
(
SELECT
COUNT(ID)
FROM
customer_migration_details
WHERE
date_opened BETWEEN '2022-01-01' AND '2022-12-31' AND customer_migration_details.Assigned_to = accounts.email GROUP BY `accounts`.`email` LIMIT 1
) AS 'New Customers'
FROM
customer_migration_details
RIGHT JOIN accounts ON customer_migration_details.Assigned_to = accounts.email
WHERE
date_opened BETWEEN '2022-01-01' AND '2022-12-31' AND customer_migration_details.Assigned_to = accounts.email AND accounts.role LIKE '%Sales%'
GROUP BY
`accounts`.`email`
這是結果
但這是煩人的部分。
Showing rows 0 - 7 (8 total, Query took 109.5797 seconds.)
子查詢中肯定缺少某些東西,也許這就是導致這需要這么長時間的原因。
使用帶有GROUP BY
的JOIN
或使用相關的子查詢,但不能同時使用。
SELECT
accounts.first_name,
accounts.last_name,
accounts.email,
COUNT(customer_migration_details.id) AS new_customers
FROM
accounts
LEFT JOIN
customer_migration_details
ON customer_migration_details.assigned_to = accounts.email
AND customer_migration_details.date_opened BETWEEN '2022-01-01' AND '2022-12-31'
WHERE
accounts.role LIKE '%Sales%'
GROUP BY
accounts.email
要么...
SELECT
accounts.first_name,
accounts.last_name,
accounts.email,
(
SELECT
COUNT(ID)
FROM
customer_migration_details
WHERE
date_opened BETWEEN '2022-01-01' AND '2022-12-31'
AND assigned_to = accounts.email
)
AS new_customers
FROM
accounts
WHERE
accounts.role LIKE '%Sales%'
筆記:
在列名中放置空格等是不好的做法,因此我將New Customers
更改為new_customers
。
LIKE '%Sales%'
不能使用索引,因此將掃描每個帳戶行。
acc: INDEX(email)
cmd: INDEX(Assigned_to, date_opened)
在子查詢中使用GROUP BY acc.email
似乎是錯誤的。 並且在外部查詢中可能是不必要的。
不要說COUNT(x)
除非您需要避免使用x IS NULL
對行進行計數。 相反,只需說`COUNT(*)。
如果date_opened
是一個DATETIME
,那么您已經排除了除夕夜以外的所有時間。
帶有初始通配符的LIKE
是一個性能問題。 是否有多個帶有“銷售”的“角色”?
當我看到RIGHT JOIN
時,我的大腦變得混亂。 它可以轉為LEFT JOIN
嗎? 無論如何,它似乎是一個INNER JOIN
。
請提供EXPLAIN SELECT...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.