我们知道当我们在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,它会有什么区别?我该如何提高性能?
谢谢