MySQL chat system to display last message of sender/receiver AND name of other person

StackOverflow https://stackoverflow.com/questions/22999060

  •  01-07-2023
  •  | 
  •  

سؤال

I'm developing a chat system and the conversation list must display 2 things:

  1. last message of whoever sent the message (me a.k.a. current user, or other user)
  2. name of other user

The part where I'm having issues is the second point. The current query displays the last message of each conversation, but in the cases where me (current user) sent the last message, instead of my name it should be displaying the other user's name.

SELECT SQL_CALC_FOUND_ROWS
    u.id_user AS id,
    i.id_user_from,
    i.id_user_to,
    u.name AS name,
    UNIX_TIMESTAMP(i.date_msg) AS date_msg,
    i.message AS msg

    FROM inbox AS i
    INNER JOIN user AS u ON (u.id_user = i.id_user_from OR u.id_user = i.id_user_to)

    WHERE id_msg IN
    (SELECT MAX(id_msg) AS id FROM
    (
        SELECT id_msg, id_user_from AS id_with
        FROM inbox
        WHERE id_user_to = 1

        UNION ALL

        SELECT id_msg, id_user_to AS id_with
        FROM inbox
        WHERE id_user_from = 1) AS t

        GROUP BY id_with
    )

    ORDER BY i.id_msg DESC

In this example, I'm Andufo (id_user = 1). Here's a sqlfiddle link if it helps. Thanks!

هل كانت مفيدة؟

المحلول

May be this helps

SELECT SQL_CALC_FOUND_ROWS
    u.id_user AS id,
    i.id_user_from,
    i.id_user_to,
    u.name AS name,
    UNIX_TIMESTAMP(i.date_msg) AS date_msg,
    i.message AS msg

    FROM inbox AS i
    INNER JOIN user AS u ON u.id_user = IF(i.id_user_from = 1 /*me*/, i.id_user_to, i.id_user_from)

    WHERE id_msg IN
    (SELECT MAX(id_msg) AS id FROM
    (
        SELECT id_msg, id_user_from AS id_with
        FROM inbox
        WHERE id_user_to = 1

        UNION ALL

        SELECT id_msg, id_user_to AS id_with
        FROM inbox
        WHERE id_user_from = 1) AS t

        GROUP BY id_with
    )
    ORDER BY i.id_msg DESC

See IF mysql operator

نصائح أخرى

This query will help:

SELECT SQL_CALC_FOUND_ROWS
       u.id_user AS id,
       i.id_user_from,
       i.id_user_to,
       u.name AS name,
       UNIX_TIMESTAMP(i.date_msg) AS date_msg,
       i.message AS msg
    FROM inbox AS i,
         user  AS u,
         (SELECT MAX(id_msg) AS id_max,
                 id_with
              FROM (
                    SELECT id_msg,
                           id_user_from AS id_with
                        FROM inbox
                        WHERE id_user_to = 1
                    UNION ALL
                    SELECT id_msg,
                           id_user_to
                        FROM inbox
                        WHERE id_user_from = 1
                   ) AS t
              GROUP BY id_with) AS m
    WHERE i.id_msg  = m.id_max
      AND u.id_user = m.id_with
    ORDER BY i.id_msg DESC
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top