posts表和votes表之间有一对多的关系,它们连接在posts.id = votes.postid上。我想知道有多少个职位有1、2、3、5等票数。
由于Waffles的最具争议的帖子查询,编写这非常简单:
declare @VoteStats table (PostId int, up int)
set nocount on
insert @VoteStats
select
PostId,
up = sum(case when VoteTypeId = 2 then 1 else 0 end)
from Votes
where VoteTypeId in (2,3)
group by PostId
set nocount off
select up, count(*)
from @VoteStats
group by up;但是,堆栈溢出数据转储上的它在22秒钟内运行.。
我是否忽略了一种加快查询速度的明显方法,或许可以避免创建VoteStats表?
发布于 2011-09-08 21:31:26
不创建VoteStats表会产生很大的不同。减到5.5秒。
set nocount on
select up, count(*)
from (
select
PostId,
up = sum(case when VoteTypeId = 2 then 1 else 0 end)
from Votes
where VoteTypeId in (2,3)
group by PostId
) a
group by up
order by uphttp://data.stackexchange.com/stackoverflow/q/112108/
从表变量版本的执行计划来看,它看起来像是表扫描,而且对表的排序非常昂贵。
发布于 2011-09-08 22:07:52
我认为这应该更快一些,因为与其对每一张拥有VoteTypeId=2的选票加起来1,不如用VoteTypeId=2来统计选票:
with VoteCountsByPost as
(
select
p.Id as PostId,
count(v.Id) as up
from Posts p
left join Votes v on v.PostId = p.Id and v.VoteTypeId = 2
group by p.Id
)
select up, count(*)
from VoteCountsByPost
group by up
order by up另外,请注意,结果有点不同:您的查询没有考虑到没有投票的帖子。
例如,如果一个帖子使用VoteTypeId != 2进行投票,那么该帖子将与0ups一起出现。如果它没有任何票数,那么该职位将被完全排除在选举结果之外。
我不知道这是不是故意的行为。
https://codereview.stackexchange.com/questions/4635
复制相似问题