我正在尝试在两个用户之间返回第一条消息,无论是我发送了消息还是收到了消息。我编写了以下查询,它返回所有正确的线程,但似乎忽略了DISTINCT子句 - 我最终得到的结果与'someid'相同。
如何更正此查询,以便在结果'someid'列中不会返回重复值?
以下是我目前正在使用的内容:
SELECT DISTINCT CASE WHEN $userid != senderid THEN senderid ELSE GROUP_CONCAT(receivers.id SEPARATOR ', ') END someid,
CASE WHEN $userid != senderid THEN senders.username ELSE GROUP_CONCAT(receivers.username SEPARATOR ', ') END somename,
messages.body,
messages.time
FROM messages
LEFT JOIN messages_recipients AS recipients ON messages.id = recipients.messageid
LEFT JOIN users AS senders ON messages.senderid = senders.id
LEFT JOIN users AS receivers ON recipients.userid = receivers.id
WHERE recipients.userid = $userid
OR messages.senderid = $userid
GROUP BY messages.id
ORDER BY messages.time DESC
答案 0 :(得分:3)
正如@Mitch Wheat所提到的,您可能必须将DISTINCT分离为外部查询。
SELECT DISTINCT * FROM
(
SELECT CASE WHEN ... GROUP BY messages.id ORDER BY messages.time DESC
) AS inner_q
ORDER BY messages.time DESC
但请记住,DISTINCT是针对不同的记录而不是单个值(someid)。 messages.time可能会阻止你获得你想要的东西。