从SQL中选择唯一值

时间:2017-03-04 10:05:18

标签: mysql

好吧所以我试图从MySQL中选择唯一的值,但我不能成功。

基本上我试图从所有用户那里获得用户收到的最后消息

查询

SELECT DISTINCT private_messages.*,
                    users.ID AS userID,
                    users.username AS username,
                    profiles.img_url AS profileImage
                    FROM private_messages
                    INNER JOIN users ON users.username = private_messages.receiver
                    INNER JOIN profiles ON profiles.userID = users.ID
                WHERE private_messages.sender ='Admin' 
                ORDER BY private_messages.sent_at DESC

现在问题是,我想只选择来自接收者的最后消息,而不是所有消息

当前结果

enter image description here

我想要实现什么?

  • 仅显示消息NEW。我无法使用LIMIT 1,因为我收到所有用户消息(从所有用户发送)

2 个答案:

答案 0 :(得分:1)

你为max(id)

过滤了
SELECT DISTINCT private_messages.*,
                users.ID AS userID,
                users.username AS username,
                profiles.img_url AS profileImage
                FROM private_messages
                INNER JOIN users ON users.username = private_messages.receiver
                INNER JOIN profiles ON profiles.userID = users.ID
            WHERE private_messages.sender ='Admin' 
            AND  private_messages.id in  ( select max(id) 
                  from private_messages group by sender 
   )                
  ORDER BY private_messages.sent_at DESC

答案 1 :(得分:0)

如果我正确理解,如果您有用户bla作为接收者用户,则需要获取所有用户发送给他的所有最新消息。

如果是这样,试试这个

SELECT private_messages.*,
            users.ID AS userID,
            users.username AS username,
            profiles.img_url AS profileImage 
FROM private_messages INNER JOIN (
    SELECT MAX(id) as maxid from private_messages 
    where receiver = 'bla'
    group by sender
) m
ON private_messages.id = m.maxid
INNER JOIN users ON users.username = private_messages.sender 
INNER JOIN profiles ON profiles.userID = users.ID
ORDER BY private_messages.sent_at DESC