使用SQL获取每两个客户端的最新消息

时间:2014-09-01 15:34:31

标签: android sql sqlite

我正在开发某种聊天应用。我将每条消息存储在SQLite表中,如下面的

|   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请求。换句话说,我需要为每对两个订阅者获取最新消息。

我想这是一个经常出现的问题,但我找不到任何可行的解决方案(或者我无法正确使用它们)。

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT * 
FROM chat c
WHERE NOT EXISTS 
 (SELECT * FROM chat 
 WHERE c.fromId IN (fromId, toId) AND c.toID IN (fromId, toID) AND c.id < id);

http://sqlfiddle.com/#!7/d57f3/2/0

答案 1 :(得分: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应该能够为每个子查询使用索引。

答案 2 :(得分: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