2014-09-01 109 views
0

我正在開發某種聊天應用程序。我在一個SQLite表的每封郵件存儲諸如以下使用SQL爲每兩個客戶端獲取最新消息

| id | fromId | toId | date | content | 
--------------------------------------------- 
|  0 | 1423 |  90 | ... |  ... | 
|  1 | 324 |  90 | ... |  ... | 
|  2 |  90 | 324 | ... |  ... | 
|  3 |  43 | 1423 | ... |  ... | 
|  4 | 439 | 324 | ... |  ... | 
|  5 |  90 | 324 | ... |  ... | 
|  6 | 324 |  43 | ... |  ... | 

我想寫一個SQL請求,顯示聊天對話框預覽。換句話說,我需要爲每兩個訂閱者獲得最新的消息。

我想這是一個頻繁的問題,但我找不到任何工作解決方案(或我無法正確使用它們)。

+0

你有沒有試過寫任何東西? – 2014-09-01 15:36:47

回答

1

如果您對chat(fromid, toid)chat(toid, fromid)索引,那麼最有效的方式可能是:

select c.* 
from chat c 
where not exists (select 1 
        from chat c2 
        where c2.fromId = c.fromId and c2.toId = c.toId and c2.id > c.id 
       ) and 
     not exists (select 1 
        from chat c2 
        where c2.fromId = c.toId and c2.toId = c.fromId and c2.id > c.id 
       ); 

的SQLite應該能夠使用每個子查詢的索引。

1

小提琴: http://sqlfiddle.com/#!7/3f4c2/2/0

select t.* 
    from tbl t 
where id = (select max(x.id) 
       from tbl x 
       where (x.fromid = t.fromid and x.toid = t.toid) 
       or (x.fromid = t.toid and x.toid = t.fromid)) 

在撥弄我創建這些索引:

create index fromto on tbl (fromid, toid); 
create index tofrom on tbl (toid, fromid); 

要告訴你,這一解決方案將利用他們:

enter image description here

相關問題