我遇到了MySQL JOIN和SUM的问题。因为我的JOIN有多个匹配,所以我会在JOIN中做一个SELECT,所以它不会太多。
问题:
我的查询非常慢。在下面的测试设置中,它只运行1毫秒,没有任何索引。但是在我的生产数据库中,只选择一条记录(WHERE id = X
)时,此查询大约需要4秒。
表a有~700,000条记录
表b有~800.000条记录
表c有~45,000条记录
表a在id
上有索引
表b包含id
,a_id
的索引
表c的索引为id
,a_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
中具有引用的c
和a
之和时。
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;
答案 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