此问题已经在这里有了答案:
我正在使用mysql编写消息系统。当我列出与之交谈的用户时,一切正常,直到我想添加对话的最后日期或对话开始。当我添加a.date
时,如果日期不相同,则会得到重复的结果。
这里是我的sqlfiddle
因为您只拉了user_id,所以在两种情况下(发送/接收),它都为您提供了独特的记录。但是到目前为止,它不再是唯一的。您需要执行以下操作:
SELECT temp.id_user, MAX(temp.date) as date
FROM
(
SELECT users.id_user,
a.date
FROM users
LEFT JOIN message AS a
ON users.id_user = a.id_user_recipient
LEFT JOIN message AS b
ON a.id_user_recipient = b.id_user_sender
WHERE a.id_user_sender = 1
UNION DISTINCT
SELECT users.id_user,
a.date
FROM users
LEFT JOIN message AS a
ON users.id_user = a.id_user_sender
LEFT JOIN message AS b
ON a.id_user_sender = b.id_user_recipient
WHERE a.id_user_recipient = 1
) as temp
GROUP BY temp.id_user;
抓取最大值(日期)将确保仅返回一条记录,与group by
相同