2017-03-04 88 views
1

好的,所以我試圖從MySQL中選擇唯一的值,但我並沒有成功。所有用戶從SQL中選擇唯一值

查詢

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

我想實現什麼?

  • 只有消息新顯示。我不能使用限制1,因爲我得到所有用戶的信息(從所有用戶發送)
+0

,那麼爲什麼你在查詢中使用'private_messages.sender =「管理員」'?你必須使用'private_messages.receiver ='bla''不應該? –

回答

1

您shoudd篩選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 
+0

謝謝! –

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