简体   繁体   中英

Mysql select distinct and all columns

I have a table named messages with this set up:

`id` is the primary key.
`from` is the current user.
`to` is the receiver of the message.
`by` is the sender of the message.
`date` is the date of the message. its the time() function from php.

I want to write a statement to select all the unique to users. Also I want select the last message sent from from to to and order the by date DESC . I only have from variable to provide into the query. I have this code but it only works partially. It does not pull the latest message between the 2 users.

$get_messages = $mysqli->query("SELECT DISTINCT `id`, `from`, `to`, `by`, `date`, `message`, `seen` FROM `messages` GROUP BY `to` WHERE `from` = '$from' ORDER BY `date` DESC");

What am I doing wrong here? Please help!

If I understand you correctly, you want the latest message from to user on the specified from user.

SELECT  a.*
FROM    messages a
        INNER JOIN
        (
            SELECT  m.to, MAX(date) max_date
            FROM    messages m
            WHERE   m.from = @from
            GROUP   BY m.to
        ) b ON a.to = b.to
                AND a.date = b.max_date
WHERE   a.from = @from
ORDER   BY a.date DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM