0

所以我试图根据他们的历史(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,我会得到完全不同的日期范围。

我曾尝试使用 DISTINCT,但也没有像样的回应。

看一下比较表的结果。

在此处输入图像描述 在此处输入图像描述

如果没有重复的contactId,我很难获得最新的项目。

任何帮助将不胜感激......我确信这是超级基本的,只是不确定为什么它不能最好地工作。

4

1 回答 1

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

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

于 2013-06-28T23:57:54.893 回答