Private messaging system. Listing last message of each conversation

前端 未结 3 1429
梦如初夏
梦如初夏 2021-02-15 17:58

Lets say this is the database structure:

\"enter

SELECT * FROM `pms` where         


        
3条回答
  •  悲&欢浪女
    2021-02-15 18:54

    This query should work:

    SELECT a.*
    FROM pms a
         INNER JOIN (
                     SELECT id_to, id_from, MAX(fecha) AS fecha
                     FROM pms
                     WHERE (id_to = 1 OR id_from = 1)
                     GROUP BY LEAST(id_to, id_from)
                    ) b
                    ON a.fecha = b.fecha AND
                       (a.id_to = b.id_to OR
                       a.id_from = b.id_from);
    

    See example @ sqlfiddle here

    If you have id as PRIMARY KEY and you are logging messages in a chronological order, then it can be further optimized and simplified as:

    SELECT a.*
    FROM pms a
         INNER JOIN (
                     SELECT MAX(id) AS id
                     FROM pms
                     WHERE (id_to = 1 OR id_from = 1)
                     GROUP BY LEAST(id_to, id_from)
                    ) b
                    ON a.id = b.id;
    

提交回复
热议问题