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

统计每个用户日志 求高效sql
用户日志统计 表A
id userid blogCount
1 100 0
2 101 0
3 102 0

日志表 表B
id userid Title  
1 100 日志1
2 102 日志1
3 100 日志1
4 101 日志1
5 101 日志1
6 102 日志1
7 102 日志1
8 101 日志1
9 102 日志1

结果 
用户统计 表A
id userid blogCount
1 100 2
2 101 3
3 102 4

需求 统计每个用户的日志总数 相应的插入统计表中 
小弟 之前想的是 循环统计表 每条对应用户ID 去统计 
请教大师们 有什么性能好的便利的sql。。 求学习

------解决方案--------------------
SQL code
--> --> (Roy)生成測試數據
 
if not object_id('A') is null
    drop table A
Go
Create table A([id] int identity,[userid] int,[blogCount] int)
Insert A
select 100,0 union all
select 101,0 union all
select 102,0
Go
--> --> (Roy)生成測試數據
 
if not object_id('B') is null
    drop table B
Go
Create table B([id] int,[userid] int,[Title] nvarchar(3))
go
Create trigger tr_B_insert on B 
for insert
as
set nocount on ;
begin
update A
set [blogCount]=a.[blogCount]+b.con
from(select [userid],count(ID) as con from inserted group by [userid]) as B
inner join A on b.[userid]=a.[userid]

insert A
select b.*
from(select [userid],count(ID) as con from inserted group by [userid]) as B
left join A on b.[userid]=a.[userid]
where a.[userid] is null
end
go

--测试
Insert B
select 1,100,N'日志1' union all
select 2,102,N'日志1' union all
select 3,100,N'日志1' union all
select 4,101,N'日志1' union all
select 5,101,N'日志1' union all
select 6,102,N'日志1' union all
select 7,102,N'日志1' union all
select 8,101,N'日志1' union all
select 9,102,N'日志1'
Go
Select * from A
/*
id    userid    blogCount
1    100    2
2    101    3
3    102    4
*/

------解决方案--------------------
SQL code
update t set blogCount=(select count(*) from 表B where userid=t.userid) from 表A t