比如:我有这样一个聊天的数据库:
id:ID
ni:你
wo:我
yuju:聊天语句
tim:聊天时间
这个mssql数据表里面就是聊天内容,现在用什么样的sql语句获得某人最近联系人记录?最近联系人包括此人发送给别人的和别人发送给此人的所有最新聊天的人,相当于qq等的最近联系人功能,具体sql语句怎么写?不要用另外表记录联系人的方法。问题补充: 请注意:这个问题不是把聊天记录按倒序排序,因为同一个人会有多条聊天,同一个人的只能取一个,并且不管是我发给对方聊天,还是对方发给我聊天,都算最近联系人。谢谢。另外,我要的是在asp.net中直接可以用的sql语句,而不是写在mssql里的存储过程等代码,谢谢。

解决方案 »

  1.   

    create table tb
    (
      id int identity,
      user1 varchar(10),
      user2 varchar(10),
      content varchar(8000),
      tim datetime
    )
    insert into tb
    select 'u1','u2','aaaaaaaaaaa',GETDATE() union all
    select 'u2','u5','aaaaaaaaaaa',GETDATE()-1 union all
    select 'u4','u1','aaaaaaaaaaa',GETDATE()-2 union all
    select 'u3','u2','aaaaaaaaaaa',GETDATE()+1 union all
    select 'u2','u1','aaaaaaaaaaa',GETDATE()+2 union all
    select 'u4','u3','aaaaaaaaaaa',GETDATE()-2 union all
    select 'u3','u2','aaaaaaaaaaa',GETDATE()+1 select user1,tim from(
    select ROW_NUMBER()over(partition by user1 order by tim desc) as rn,user1,tim
    from
    (
    select user1,tim
    from tb
    union all
    select user2,tim
    from tb
    )a) aa
    where rn=1
    /*
    ------------------
    user1 tim
    u1 2011-01-13 09:02:20.503
    u2 2011-01-13 09:02:20.503
    u3 2011-01-12 09:02:20.503
    u4 2011-01-09 09:02:20.503
    u5 2011-01-10 09:02:20.503
    */
      

  2.   

    select t.* from tb t where tim = (select max(tim) from tb where id = t.id)
    select t.* from tb t where not exists (select 1 from tb where id = t.id and tim > t.tim)
      

  3.   


    select case when ni = '某人' then wo else ni end 
    from 表名 
    where ni='某人' or wo = '某人' 
    group by case when ni = '某人' then wo else ni end 
    order by max(tim) desc
    楼主,记得结贴哦
      

  4.   

    我擦 大大的SQL每次都看的我心跳
      

  5.   

    select distinct top 50 (case when ni='某人' then wo else ni end) as 联系人 
    from tb where ni='某人' or wo='某人' order by tim desc
      

  6.   

    非常感谢大家的回复,但我看估计没有可用的。6楼的测试结果:
    1、不能过滤同一个人的聊天。比如张三向我聊了3句,最近联系人的张三就重复3次。
    2、只能显示发送人名,不能显示接收人命,我的要求应该包含了两者:select ni, wo,因为不确定是ni是我还是wo是我,因为是互动的聊天。
    3、只显示发送的记录,不显示接收的记录。
    呵呵,其他的我再测试看看,暂时只能测试sql语句的。
    希望有更大的虾提供更好的sql语句!
      

  7.   

    coleling 真是人中龙凤,sql不俗,确有奇用,顷此贴之分相赠。其他朋友也有苦劳,聊以1分相赠。谢谢大家!