环境是sqlserver 2008
一张聊天表
CREATE TABLE [dbo].[SNS_Chat]( [ChatID] [uniqueidentifier] NOT NULL, [UserID] [uniqueidentifier] NULL, [ToUserId] [uniqueidentifier] NULL, [Content] [varchar](400) NULL, [CreateTime] [datetime] NULL, ) ON [PRIMARY]
一张最后查看时间表
CREATE TABLE [dbo].[SNS_LastRead]( [ID] [int] IDENTITY(1,1) NOT NULL, [UserID] [uniqueidentifier] NULL, [ToUserId] [uniqueidentifier] NULL, [LastReadTime] [datetime] NULL, )
希望能通过一个sql文(可以用2008的相关特性,不一定非要一个sql,只是不想写存储过) 统计出所有未读消息数量(所有人的未读消息数量加在一起)
判断标准是啥?LastReadTime大于CreateTime的都算是阅读过的?
是的,就是两个时间比较
@HA-LOU:
SELECT COUNT(t2.[ChatID]) FROM [SNS_LastRead] t1 LEFT JOIN [SNS_Chat] t2 ON t1.[UserID]=t2.[UserID] AND t1.[ToUserId]=t2.[ToUserId] AND t1.[LastReadTime]<t2.[CreateTime]
@幻天芒: 基本可用,稍改了下,一直纠结在group,看来sql文的理解理还是差太多。谢谢
SELECT count(*) FROM [SNS_LastRead] t1 inner JOIN [SNS_Chat] t2 ON t1.[UserID]= t2.[ToUserId] AND t1.[ToUserId]=t2.[UserID] AND t1.[LastReadTime]<t2.[CreateTime]
@HA-LOU:Yeah~
因你是把所有人的未读消息求和,所以与上面的表没有关系了直接对下面的表 LastReadTime字段求和就行了
select Count(LastReadTime) from SNS_LastRead where ISNULL(LastReadTime,'')=''
这样就行了