我正在开发某种聊天应用。我将每条消息存储在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请求。换句话说,我需要为每对两个订阅者获取最新消息。
我想这是一个经常出现的问题,但我找不到任何可行的解决方案(或者我无法正确使用它们)。
答案 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);
答案 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);
告诉您此解决方案将使用它们: