sql:查出每個聯繫人最新的1條消息

要從數據庫的消息表裏查出最近跟哪些人聊了天,從而生成聊天列表。
麻煩點:

  1. 消息裏我可以是發送者也是接收者,還有可能不是我的消息,有其他人登錄過了
  2. 每個人最新的,而不是一起最新的,要分組

這是初始數據:


第一步先生成一箇中間表:

select id, (case 
    when sender=0 then receiver
    when receiver=0 then sender 
    else -1 end)other, time, msg from message ;

用了一個case when,判斷髮送者是我,那麼就取接受者,接收者是我,就取發送者,否則取-1,因爲id都是正數,後面用來剔除。


第二步使用other分組,但是如果使用group by,那麼每一列要獨立的使用聚合函數,比如:

select max(id), other, max(time),max(msg) from (select id, (case 
    when sender=0 then receiver
    when receiver=0 then sender 
    else -1 end)other, time, msg from message) o group by other;

msg那一列我們肯定是希望是time最大的時候的那條消息的msg,但各個列是獨立的聚合的,沒法指定msg使用time那一列的跟隨數據。還有id也是一樣,最大的id跟最大time可能不是在一條消息裏。

要處理這個就用到了left join:

//建了一個視圖,用來代替這個中間表
CREATE VIEW user_other AS
select id, (case 
    when sender=0 then receiver
    when receiver=0 then sender 
    else -1 end)other, time, msg from message ;

select u1.id, u1.other, u1.time, u1.msg from
      user_other u1 
    left join user_other u2 on
    u1.other = u2.other and u1.time<u2.time
    where u2.time is null and u1.other != -1;

left join的時候,重點是where u2.time is null這個,當沒有比u1.time更大的u2.time的時候,它就是null,這也表示這時u1.time是最大的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章