我有一个在超过 60 万条记录上运行的 mysql SUM 查询。我目前正在做的是这样的
SELECT SUM (payment)
FROM payment_table
WHERE
payment_date BETWEEN ... AND ...
AND
payment_status = 'paid'
我将查询更改为这种格式以减少记录集,但它仍然需要几乎相同的时间。
SELECT SUM(Payments)
FROM (
SELECT payment AS Payments FROM payment_table WHERE
payment_date BETWEEN DATE_FORMAT(NOW(), '2012-2-01') AND DATE_FORMAT(LAST_DAY(DATE_FORMAT(NOW(), '2012-2-01')), '%Y-%m-%d')
AND
payment_status = 'paid'
) AS tmp_table
他们有什么方法可以优化这个总和查询。编辑:
这是查询运行时的结果EXPLAIN
插入
` (
id,
select_type,
table,
type,
possible_keys,
key,
key_len,
ref,
rows,
Extra`) values('1','SIMPLE','lps','index_merge','assigned_user_id,scheduled_payment_date,payment_status,deleted','deleted,assigned_user_id,payment_status', '2,109,303',NULL,'23347','使用 intersect(deleted,assigned_user_id,payment_status); 使用 where');