MySQL GROUP By和ORDER BY冲突

时间:2013-06-28 23:50:31

标签: php mysql group-by distinct

所以我试图根据他们的HISTORY(TABLE1)选择一些联系人(TABLE2)。 所以我正在测试这个SQL查询:

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 个答案:

答案 0 :(得分: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

这应该给你(我没有测试过)每个用户和联系人一行,按联系人添加日期排序。