drex88669 2013-06-28 23:50
浏览 234
已采纳

MySQL GROUP By和ORDER BY冲突

So i'm trying to select some contacts (TABLE2) based on their HISTORY (TABLE1). So I am testing with this SQL Query:

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

But i'm noticing that i'm not getting the most 'recent' values. If I remove the GROUP BY I get totally different DATE RANGES.

I have tried using DISTINCT, but no decent response either.

Take a look at the comparison table results.

enter image description hereenter image description here

I'm having a hard time getting the most recent items, without having duplicate contactId's in there.

Any help would be greatly appreciated... i'm sure this is super basic, just not sure why it's not working the best.

  • 写回答

1条回答 默认 最新

  • duafagm1066 2013-06-28 23:57
    关注

    GROUP BY is for use with aggregate methods. Without something like MAX(contacts_history.dateAdded) it doesn't make any sense to use GROUP BY

    I think what you want is along the lines:

    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
    

    This should give you (I haven't tested it) one line for each user and contact, sorted by the date the contact was added.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?