我创建了一个查询,它从两个表中收集数据,将它们汇总并显示案例数和总和:
SELECT
count(ut.id) AS total
, ( SUM(internal_account) - SUM(( SELECT
SUM( ub.bill_summs )
FROM
u_billing ub
WHERE
ub.bill_types = 'correction'
AND ub.contract_id = ut.contract_id
)) ) AS summ
FROM
u_transactions ut
WHERE
ut.nulled = 0
AND ut.type = 'comission'
AND ut._status = 'not_paid'
AND DATE( ut.add_timestamp ) = DATE( '2012-05-11' );
但它真的很慢。在测试用例中,它给出了这样的结果:
+-------+-------+
| total | summ |
+-------+-------+
| 182 | 15105 |
+-------+-------+
1 row in set (4.13 sec)
182 个案例为 4.13 秒,仅 1 天,但我的实时服务器有超过 600k 个案例,所以这将非常慢。
任何想法,我如何重写查询以获得更好的性能?
重新制作查询的解决方案:
DELETE FROM tmpContractSums;
INSERT INTO tmpContractSums
SELECT
ub.contract_id
, SUM( ub.bill_summs ) AS bill_summs
FROM
u_billing ub
WHERE
ub.bill_types = 'correction'
GROUP BY ub.contract_id;
SELECT
count(ut.id) AS total
, ( SUM(internal_account) - SUM(bill_summs) )
FROM
u_transactions ut
LEFT JOIN tmpContractSums t ON ut.contract_id = t.contract_id
WHERE
ut.nulled = 0
AND ut.type = 'comission'
AND ut._status = 'not_paid'
AND ut.add_timestamp BETWEEN '2012-05-11 00:00:00' AND '2012-05-11 23:59:59';
执行时间:500ms
PS:由于我无法使用网络用户删除表格,因此我刚刚创建了表格:
CREATE TABLE tmpContractSums AS SELECT contract_id, bill_summs FROM u_billing WHERE 1 = 0;
我正在删除记录。不如 drop 快,但仍然比原始快得多。