0
我們知道,我們索引中的列來提高性能,當我們按該列在WHERE語句進行篩選,但如果我們這樣做:在MySQL中爲SELECT中使用的字段添加索引而不是WHERE,改進了一些內容?
SELECT
customer_id,
SUM(principal_lent) AS lifetime_total_loans,
SUM(IF(loan_created_at >= DATE_SUB(NOW(),INTERVAL 1 YEAR) and loan_created_at <= NOW(), principal_lent, 0)) AS yearly_total_loans,
SUM(IF(loan_created_at >= DATE_SUB(NOW(),INTERVAL 90 DAY) and loan_created_at <= NOW(), principal_lent, 0)) AS quarterly_total_loans,
SUM(IF(loan_created_at >= DATE_SUB(NOW(),INTERVAL 30 DAY) and loan_created_at <= NOW(), principal_lent, 0)) AS monthly_total_loans,
SUM(IF(loan_created_at >= CAST(DATE_FORMAT(NOW() ,'%Y-%m-01') as DATE) and loan_created_at <= NOW(), principal_lent, 0)) AS current_month_total_loans,
COUNT(id) AS lifetime_num_loans,
SUM(IF(loan_created_at >= DATE_SUB(NOW(),INTERVAL 1 YEAR) and loan_created_at <= NOW(), 1, 0)) AS yearly_num_loans,
SUM(IF(loan_created_at >= DATE_SUB(NOW(),INTERVAL 90 DAY) and loan_created_at <= NOW(), 1, 0)) AS quarterly_num_loans,
SUM(IF(loan_created_at >= DATE_SUB(NOW(),INTERVAL 30 DAY) and loan_created_at <= NOW(), 1, 0)) AS monthly_num_loans,
SUM(IF(loan_created_at >= CAST(DATE_FORMAT(NOW() ,'%Y-%m-01') as DATE) and loan_created_at <= NOW(), 1, 0)) AS current_month_num_loans
FROM loans
GROUP BY customer_id
領域的customer_id是一個FK因此被編入索引。
如果我索引loan_created_at,它會有什麼區別?我該如何提高性能? 感謝
索引真的只在WHERE子句和JOIN條件中幫助你(如果你正在加入一個不是PK或FK的字段)。在你的情況下,爲了加快速度,我建議將數據存儲在另一個表中,每天更新一個cron作業。 –
我可以看到可能提高績效的唯一方法就是每晚都有一份工作(清晨運行可識別貸款年齡/組),那麼您不必在每次運行時都對查詢進行所有計算;但每晚一次。任何「新/空值」都將是新創建的貸款,並將落入當月。或者,您可以使用每天晚上的查詢結果以及UNION&SUM中的任何「新」事件生成一個表格,這種方式的開銷僅限於新記錄。 – xQbert
有一個問題需要問:當你運行上述查詢時,你得到的響應時間是多少?第二個問題是:爲什麼你要無限制地查找數據(我的意思是說,你只會查找最多1歲或6個月或其他任何時期的數據) 。如果你真的需要回顧歷史的開始,你應該考慮「烹飪」你的一些數據,就像@xQbert所暗示的那樣。 – FDavidov