我有一个像
这样的查询SELECT ProductId,(SELECT COUNT(*)
FROM Log
WHERE Log.App = App.No
AND Log.Event = 54
)
FROM App
WHERE App.cat IN (1,2,3)
此查询返回100万条记录。问题是这个查询真的很慢。我有LOG(App,Event)的复合索引和App(cat)的索引。有什么方法可以加快这个查询的速度? App和Log表包含大约10M条记录
当我评论"SELECT COUNT(*) ...."
查询超快时
答案 0 :(得分:1)
您可以尝试重写查询以使用连接而不是相关子查询:
SELECT t1.ProductId,
COALESECE(t2.logCount, 0)
FROM App t1
INNER JOIN
(
SELECT t1.No, COUNT(*) AS logCount
FROM App t1
LEFT JOIN Log t2
ON t1.No = t2.App AND
t2.Event = 54
WHERE t1.cat IN (1, 2, 3)
GROUP BY t1.No
) t2
ON t1.No = t2.No
答案 1 :(得分:0)
您可以使用JOIN。因为子查询非常慢。
SELECT ProductId, COUNT(Log.*)
FROM App
LEFT OUTER JOIN Log ON Log.App = App.No AND Log.Event = 54
WHERE App.cat IN (1,2,3)