Jump to content

Distinct repeating values from 2 columns


php_nub_qq
Go to solution Solved by Barand,

Recommended Posts

Hello.

 

I have a messages table which holds all messages that users type ( chat ). What I'm trying to create is a division which holds all conversations of the user currently browsing. Much like facebook, it is supposed to hold every single person that the user has ever chatted with and the last message no matter who the sender is. My table's columns are ID, sender, recipient, message, time and seen. I know this can be done in multiple queries as well as in PHP but I'm trying to go pro on this project and thus I aim to do it in one. I'm close to achieving my goal but I just couldn't struggle anymore and I'm posting for some help

 

This is my query

SELECT `message`, `recipient`, `sender`, (SELECT `username` FROM `users` WHERE `id`=`recipient`) AS 'recipientName', (SELECT `username` FROM `users` WHERE `id`=`sender`) AS 'senderName', time, seen FROM (SELECT * FROM `messages` WHERE `recipient`='{$id}' GROUP BY `sender` UNION SELECT * FROM `messages` WHERE `sender`='{$id}' GROUP BY `recipient`) AS D 

This is really difficult to explain so I'll just give you a table of results

 

the ID for this example is 6

 

resultvr.jpg

 

 

and this is what I'm trying to get to

 

giakkm.jpg

Edited by php_nub_qq
Link to comment
Share on other sites

  • Solution

try this

SELECT m.message, m.recipient, m.sender
    , r.username as recipient_name
    , s.username as sender_name
    , m.time
    , m.seen
FROM messages m
    INNER JOIN user r ON m.recipient = r.user_id
    INNER JOIN user s ON m.sender = s.user_id
    INNER JOIN 
    (
    SELECT LEAST(recipient, sender) as a
        , GREATEST(recipient, sender) as b
        , MAX(time) as time
    FROM messages
    GROUP BY a,b
    ) as latest
    ON LEAST(m.recipient,m.sender) = latest.a
    AND GREATEST(m.recipient,m.sender) = latest.b
    AND m.time = latest.time
WHERE 6 IN (m.recipient, m.sender)
ORDER BY time DESC;

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.