Private messaging system. Listing last message of each conversation

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

Lets say this is the database structure:

\"enter

SELECT * FROM `pms` where         


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-02-15 18:50

    This assumes id is an auto-increment column:

    SELECT MAX(id) AS id
    FROM pms
    WHERE id_to = 1 OR id_from = 1
    GROUP BY (IF(id_to = 1, id_from, id_to))
    

    Assuming you have id_from and id_to indexed, this variation will most likely perform better because MySQL doesn't know what to do with an OR:

    SELECT MAX(id) AS id FROM
    (SELECT id, id_from AS id_with
    FROM pms
    WHERE id_to = 1
    UNION ALL
    SELECT id, id_to AS id_with
    FROM pms
    WHERE id_from = 1) t
    GROUP BY id_with
    

    Here's how to get the messages for those ids:

    SELECT * FROM pms WHERE id IN
        (SELECT MAX(id) AS id FROM
        (SELECT id, id_from AS id_with
        FROM pms
        WHERE id_to = 1
        UNION ALL
        SELECT id, id_to AS id_with
        FROM pms
        WHERE id_from = 1) t
        GROUP BY id_with)
    

提交回复
热议问题