Mysql选择distinct和所有列

时间:2014-09-19 09:39:18

标签: php mysql pdo mysqli

我有一个名为messages的表,设置了这个:

`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.

我想写一个语句来选择所有唯一的to用户。另外,我想选择从from发送到to的最后一条消息,并按date DESC排序。我只有from变量提供给查询。我有这个代码,但它只能部分工作。它不会在2个用户之间提取最新消息。

$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");

我在这里做错了什么?请帮忙!

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您希望to用户在指定的from用户上收到最新消息。

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