MySQL JOIN和SUM性能问题

时间:2016-12-12 10:43:48

标签: mysql join

我遇到了MySQL JOIN和SUM的问题。因为我的JOIN有多个匹配,所以我会在JOIN中做一个SELECT,所以它不会太多。

问题:
我的查询非常慢。在下面的测试设置中,它只运行1毫秒,没有任何索引。但是在我的生产数据库中,只选择一条记录(WHERE id = X)时,此查询大约需要4秒。

表a有~700,000条记录
表b有~800.000条记录 表c有~45,000条记录

表a在id上有索引 表b包含ida_id的索引 表c的索引为ida_id

简化表下方并使用了Query。

a

id
---
1

b

id | a_id | amount | price
--------------------------
 1 |    1 |      1 |    25
 2 |    1 |      1 |    20

c

id | a_id | amount | price
--------------------------
 1 |    1 |      1 |    23
 2 |    1 |      1 |    20

查询:
现在,当我运行此查询以获取表b中具有引用的ca之和时。

SELECT id, bPrice, cPrice
FROM a
LEFT JOIN (SELECT a_id, SUM(amount * price) AS bPrice FROM b GROUP BY a_id) bb ON a.id = bb.a_id
LEFT JOIN (SELECT a_id, SUM(amount * price) AS cPrice FROM c GROUP BY a_id) cc ON a.id = cc.a_id

结果错误

错误
SELECT 
    a.id,
    SUM(b.amount * b.price) AS bPrice,
    SUM(c.amount * c.price) AS cPrice
FROM a
JOIN b ON a.id = b.a_id
JOIN c ON a.id = c.a_id;

SQL Fiddle example

3 个答案:

答案 0 :(得分:2)

MySQL将很难从子查询中提取索引以加入,并怀疑你从子查询中加入了很多行。

作为初始步骤,您可以尝试删除其中一个子查询,只是将其更改为针对主表的连接。

SELECT id, 
        SUM(b.amount * b.price) AS bPrice, 
        cPrice
FROM a
LEFT OUTER JOIN b ON a.id = b.a_id
LEFT OUTER JOIN 
(
    SELECT a_id, 
            SUM(amount * price) AS cPrice 
    FROM c 
    GROUP BY a_id
) cc ON a.id = cc.a_id
GROUP BY a.id,
        cc.cPrice

答案 1 :(得分:0)

尝试以下查询:

select set1.id,set1.bPrice,set2.cPrice from (SELECT a.id,SUM(b.amount * b.price) AS bPrice FROM a JOIN b ON a.id = b.a_id) as set1
JOIN
(SELECT a.id,SUM(c.amount * c.price) AS cPrice FROM a JOIN c ON a.id = c.a_id) as set2 ON set1.id = set2.id

答案 2 :(得分:0)

可能值得尝试子查询 - 有时它们可​​以更快:

SELECT 
    id, 
    (SELECT SUM(amount * price) AS bPrice FROM b where b.a_id = a.id) AS bPrice, 
    (SELECT SUM(amount * price) AS cPrice FROM c where c.a_id = a.id) AS cPrice
FROM a