我幾個月前寫了這個查詢。它運行良好。但是,這個查詢一天比一天要慢。爲什麼這個查詢需要這麼長時間來執行
此查詢檢查除了同一個表執行以外的多個表中的帳單歷史記錄。
下面是該查詢 -
SELECT * FROM (
SELECT *,
(SELECT username FROM users WHERE id = u_bills.UserId) AS username,
(SELECT first_name FROM users WHERE id = u_bills.UserId) AS first_name,
(SELECT last_name FROM users WHERE id = u_bills.UserId) AS last_name,
(SELECT phone FROM users WHERE id = u_bills.UserId) AS phone,
(SELECT email FROM users WHERE id = u_bills.UserId) AS email,
(SELECT CPRate FROM cpt WHERE UserId = u_bills.UserId ORDER BY AddedDate DESC LIMIT 0,1) AS cprate,
(SELECT (SELECT PopName FROM pops WHERE PopId = p.PopName) AS PopFullName FROM u_setupinfos AS p
WHERE UserId = u_bills.UserId) AS popname,
(SELECT active FROM users WHERE id = u_bills.UserId) AS active,
(SELECT SUM(PaidAmount) AS PaidAmount FROM u_billhistory
WHERE UserId = u_bills.UserId AND MONTH(AddedDate) = MONTH(PaidDate)) AS PaidAmount,
(SELECT PaidDate FROM u_billhistory
WHERE UserId = u_bills.UserId AND MONTH(AddedDate) = MONTH(PaidDate)
GROUP BY MONTH(PaidDate)) AS PaidDate,
(SELECT PaymentMedia FROM u_billhistory
WHERE UserId = u_bills.UserId AND MONTH(AddedDate) = MONTH(PaidDate)
GROUP BY MONTH(PaidDate)) AS PaymentMedia,
(SELECT TransactionId FROM u_billhistory
WHERE UserId = u_bills.UserId AND MONTH(AddedDate) = MONTH(PaidDate) GROUP BY MONTH(PaidDate)) AS TransactionId,
(SELECT GROUP_CONCAT(CONCAT(`BillHisId`,';',`PaidAmount`,';',`PaidDate`) separator '|') AS vals
FROM u_billhistory
WHERE UserId = u_bills.UserId
AND YEAR(PaidDate) = YEAR(CURDATE())) AS TotalPaids
FROM u_bills) AS m
WHERE m.username = 'abc'
請查閱圖像 -
我想組織此查詢的EXPLAIN
報告。我需要建議使這個查詢更快,例如3到5秒,而不是1分半鐘或更長。我在這個查詢中犯了什麼錯誤?
重要筆記記錄
也許沒有 - 您是否更新過服務器上的統計信息?那段時間你的數據如何增長?還有其他數據庫爭奪資源嗎? –
這就是說 - 爲什麼所有的子查詢一次只能得到一個字段? –
,因爲它的巨大與subquerys –