SQL性能GROUP BY vs UNION

时间:2015-01-23 20:08:01

标签: sql sql-server performance tsql

我使用GROUP BY与UNION的表现不佳。见下文

使用GROUP BY,约17秒

select b.BookTypeKey, count(b.BookKey) 
from Books b
where contains(b.BookTitle, @SearchTerm)
group by b.BookTypeKey

使用UNION,~1-2秒

select '1' as BookTypeKey, count(b.BookKey)
from Books b
where contains(b.BookTitle, @SearchTerm) and b.BookTypeKey = 1

union

select '2' as BookTypeKey, count(b.BookKey)
from Books b
where contains(b.BookTitle, @SearchTerm) and b.BookTypeKey = 2

union

select '3' as BookTypeKey, count(b.BookKey)
from Books b
where contains(b.BookTitle, @SearchTerm) and b.BookTypeKey = 3

有什么想法?理想情况下,我不想使用三个单独的UNION语句来执行此操作。仅供参考,只有三种" BookTypes" (1,2和3)

1 个答案:

答案 0 :(得分:0)

评论太长了。你说只有三种书类型,但你确定吗?这个查询返回了什么:

select b.BookTypeKey, count(b.BookKey) 
from Books b
group by b.BookTypeKey;

NULL在这里是非常重要的考虑因素。我希望contains()会对性能产生重大影响。但是,两个版本的查询都会调用contains()相同的次数 - 除非BookTypeKey的值超过三个。否则,contains()group by之间可能会发生一些奇怪的互动。

此外,union all在第二个查询中的性能稍好一些。