首先,例如我有3个表A,B,C。表A与表B有关系,表与表C有关系。我想得到表A中某些字段的SUM,这取决于某些字段来自表C.
表A具有> 300k行,表B具有> 4k行,表C有~100行
我的查询如下:
SELECT SUM(a.hours) AS total
FROM table_a a
LEFT JOIN table_b b
ON a.table_b_id = b.id
LEFT JOIN table_c c
ON b.table_c_id = c.id
WHERE a.customer_id = 1
AND c.title IN ('Title D','Title E')
查询执行时间约为7秒,非常慢。但是如下所述的查询执行时间约为0.0秒。
SELECT a.hours
FROM table_a a
LEFT JOIN table_b b
ON a.table_b_id = b.id
LEFT JOIN table_c c
ON b.table_c_id = c.id
WHERE a.customer_id = 1
AND c.title IN ('Title D','Title E')
为什么SUM太慢了?我该怎么办?
答案 0 :(得分:1)
将条件移至相关表的ON
子句:
SELECT SUM(a.hours) AS total
FROM table_a a
LEFT JOIN table_b b
ON a.table_b_id = b.id
LEFT JOIN table_c c
ON b.table_c_id = c.id
AND c.title IN ('Title D','Title E')
WHERE a.customer_id = 1
编辑1 根据@dnoeth评论,我同意,加入inner join
时我们可能应该使用table_c
:
SELECT SUM(a.hours) AS total
FROM table_a a
LEFT JOIN table_b b
ON a.table_b_id = b.id
INNER JOIN table_c c
ON b.table_c_id = c.id
AND c.title IN ('Title D','Title E')
WHERE a.customer_id = 1
答案 1 :(得分:0)
在两个地方使用LEFT JOIN
并添加此综合索引:
INDEX(customer_id, title)