MySQL多组使用

时间:2014-08-18 01:37:17

标签: mysql group-by

现在我使用这个是查询:

SELECT * FROM messages WHERE ReceiverID='$uid' or SenderID='$uid' GROUP BY Recei
verID,SenderID ORDER BY Datex DESC

但他们的结果

ID  ReceiverID  SenderID
 1      2            1
 2      1            2

但我想只显示WHERE语法的一个结果。 例如:

ID  ReceiverID  SenderID
 1      2            1

ID  ReceiverID  SenderID
 2      1            2

3 个答案:

答案 0 :(得分:0)

您想使用least()greatest()

SELECT *
FROM messages
WHERE ReceiverID='$uid' or SenderID='$uid'
GROUP BY least(ReceiverID, SenderID), greatest(ReceiverID, SenderID)
ORDER BY Datex DESC;

但是,您应该在select中明确列出列。您正在使用MySQL扩展,其中select中的列不在group by中。除非你明白自己在做什么,否则这是一个坏主意。

答案 1 :(得分:0)

HI尝试此查询,

SELECT * FROM messages(SELECT * FROM messages ORDER BY Datex DESC) WHERE  ReceiverID='$uid' or SenderID='$uid' GROUP BY ReceiverID,SenderID

答案 2 :(得分:0)

如果你想要的只是一个而且它可以是一个那么为什么不只是做一个有限制的随机排序?

SELECT id, recieverid, senderid 
FROM
(   SELECT * 
    FROM messages 
    WHERE ReceiverID='$uid' OR SenderID='$uid' 
    GROUP BY ReceiverID,SenderID 
    ORDER BY Datex DESC
) t
ORDER BY RAND()
LIMIT 1