【发布时间】:2011-05-21 06:38:14
【问题描述】:
我正在使用 MS SQL。
我有一个带有索引的巨大表来加快这个查询:
select userid from IncrementalStatistics where
IncrementalStatisticsTypeID = 5 and
IncrementalStatistics.AssociatedPlaceID = 47828 and
IncrementalStatistics.Created > '12/2/2010
它会在不到 1 秒的时间内返回。该表有数十亿行。只有大约 10000 个结果。
我希望这个查询也能在大约一秒钟内完成:
select userid from IncrementalStatistics where
IncrementalStatisticsTypeID = 5 and
IncrementalStatistics.AssociatedPlaceID = 47828 and
IncrementalStatistics.Created > '12/2/2010'
intersect
select userid from IncrementalStatistics where
IncrementalStatisticsTypeID = 5 and
IncrementalStatistics.AssociatedPlaceID = 40652 and
IncrementalStatistics.Created > '12/2/2010'
intersect
select userid from IncrementalStatistics where
IncrementalStatisticsTypeID = 5 and
IncrementalStatistics.AssociatedPlaceID = 14403 and
IncrementalStatistics.Created > '12/2/2010'
但这需要 20 秒。所有单个查询都需要
我希望 SQL 在内部将这些子查询中的每一个的结果放入哈希表并进行哈希交集 - 应该是 O(n)。结果集足够大,可以放入内存,所以我怀疑这是 IO 问题。
我编写了一个替代查询,它只是一系列嵌套的 JOIN,这也需要大约 20 秒,这是有道理的。
为什么 INTERSECT 这么慢?它是否在查询处理的早期阶段减少为 JOIN?
【问题讨论】:
-
“我怀疑这是一个 io 问题”-> 解释计划说查询中最昂贵的部分是什么?
-
MS SQL 是否有 EXPLAIN 或某种方式来查看查询计划?根据其他人的回答,听起来 INTERSECT 实现并不聪明......
-
@Brendan - 是的,查询计划有一个很好的可视化。这个查询似乎不够微妙,不需要求助 - 我正在寻找直观的论点。
标签: sql algorithm join query-optimization intersect