2013-06-28 140 views
0

所以我試圖根據他們的HISTORY(TABLE1)選擇一些聯繫人(TABLE2)。 所以我這個SQL查詢測試:MySQL GROUP By和ORDER BY衝突

SELECT 
    contacts_history.userId, 
    contacts_history.contactId, 
    contacts_history.dateAdded, 
    contacts.firstName 
FROM 
    contacts_history 
INNER JOIN contacts ON contacts_history.contactId = contacts.contactId 
AND contacts_history.userId = contacts.userId 
GROUP BY 
    contacts.contactId 
ORDER BY 
    contacts_history.dateAdded DESC 
LIMIT 0, 10 

,但我注意到,我沒有得到最「近」的值。 如果我刪除GROUP BY,我會得到完全不同的DATE RANGES。

我試過使用DISTINCT,但沒有像樣的迴應。

看看比較表結果。

enter image description here enter image description here

我有一個很難得到的最新的項目,而不必在那裏重複的ContactID的。

任何幫助將不勝感激......我敢肯定,這是超級基礎,只是不知道爲什麼它不是最好的。

回答

1

GROUP BY適用於聚合方法。如果沒有類似MAX(contacts_history.dateAdded)它沒有任何意義,用GROUP BY

認爲你想要的是沿線:

SELECT 
    contacts_history.userId, 
    contacts_history.contactId, 
    MAX(contacts_history.dateAdded) AS last_date, 
    contacts.firstName 
FROM 
    contacts_history 
INNER JOIN contacts ON contacts_history.contactId = contacts.contactId 
AND contacts_history.userId = contacts.userId 
GROUP BY 
    contacts_history.userId, 
    contacts.contactId 
    contacts.firstName 
ORDER BY 
    last_date DESC 
LIMIT 0, 10 

這應該給你(我沒有測試它)一個爲每個用戶和聯繫人添加一行,按聯繫人的添加日期排序。

+0

感謝人......一直在做一些SQL,忘了簡單的事情。 – Justin