我正在尝试获取与我在消息系统中交互过的用户列表:
表:
messages: id, sender_id, recipient_id, message, date
SQL:
SELECT * FROM `messages`
WHERE
(`sender_id` = :user_id OR `recipient_id` = :user_id)
GROUP BY `sender_id`, `recipient_id`
ORDER by `date` DESC
这给了我多行发件人/收件人 ID 不匹配的
我认为是 GROUP BY
导致的,不确定如何修复它
编辑:每次交互我只需要 1 行(因此 GROUP BY
)
最佳答案
GROUP BY
将合并具有相同 sender_id
和 recipient_id
的所有行。使用 UNION
将两个组合并为一组结果:
SELECT correspondent, MAX(date) AS last_date
FROM (
SELECT sender_id as correspondent, date
FROM messages
WHERE recipient_id = :user_id
UNION ALL
SELECT recipient_id as correspondent, date
FROM messages
WHERE send_id = :user_id) x
GROUP BY correspondent
ORDER BY last_date DESC
关于mysql - 如何获取我在消息系统中与之交互的用户列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28819285/