日期:2014-05-18  浏览次数:20748 次

求一sql指令:统计主贴的回帖数量
有数据库表t,字段如下,想更新replies字段的值,如何写sql指令?
C# code

这是原来表的数据:
id    replies    zid
1    0    0
2    0    0
3    0    1
4    0    1
5    0    2
6    0    1

这是更新后应该有的结果:
id    replies    zid
1    3    0
2    1    0
3    0    1
4    0    1
5    0    2
6    0    1


若zid=0,说明是主贴
若zid=1,表示该贴是id=1的主贴的回帖

------解决方案--------------------
你定义一个游标也可以实现:

declare @id int
declare cur cursor
for 
select id from t where zid=0
open cur 
 fetch next from cur into @id 
while @@Fetch_status = 0
begin
 update t set replies=(select count(*) from t where zid =@id) where zid=0 and id=@id
fetch next from cur into @id
end
select * from t
close cur
deallocate cur
------解决方案--------------------
update tb set replies=(select isnull(count(*),0) from Tb a where a.id=id) where zid=0

------解决方案--------------------
探讨
引用:
update tb set replies=(select isnull(count(*),0) from Tb a where a.id=id) where zid=0


经多次变样测试,下面的指令不能得到正确的结果:
update t set replies=(select count(*) from t a where a.zid=id) w……