【问题标题】:Get the latest message for each two clients using SQL使用 SQL 获取每两个客户端的最新消息
【发布时间】:2014-09-01 15:34:31
【问题描述】:

我正在开发某种聊天应用程序。我将每条消息都存储在 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 请求。换句话说,我需要为每对两个订阅者获取最新消息。

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

【问题讨论】:

  • 你试过写什么吗?

标签: android sql sqlite


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    如果您在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 应该能够为每个子查询使用索引。

    【讨论】:

      【解决方案3】:

      小提琴: 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);
      

      向您展示此解决方案将利用它们:

      【讨论】:

        猜你喜欢
        • 2016-11-02
        • 1970-01-01
        • 1970-01-01
        • 2019-04-13
        • 2014-11-04
        • 1970-01-01
        • 2014-01-18
        • 2012-08-08
        • 1970-01-01
        相关资源
        最近更新 更多