MYSQL GROUP BY未显示正确的日期

时间:2017-04-16 19:44:12

标签: mysql group-by

我遇到了MYSQL v.5.7.15-log中GROUP BY函数的一个小问题。

SELECT ca.CategoryID, ca.CategoryName, ca.CategoryDescription, co.Commenter, co.CommentDate 
FROM forum_category AS ca 
JOIN forum_comment AS co 
    ON co.CategoryID = ca.CategoryID
ORDER BY ca.CategoryID ASC, co.CommentDate DESC

导致

CategoryID  CategoryName    CategoryDescription Commenter   CommentDate
1           Admin           test1               Pino        "2017-04-16 15:47:41"
1           Admin           test1               Pino        "2017-04-16 15:36:40"
1           Admin           test1               Pino        "2017-04-16 15:25:30"
2           test            bla                 Pino        "2017-04-16 17:17:56"
2           test            bla                 Pino        "2017-04-16 17:17:21"
2           test            bla                 Pino        "2017-04-16 15:56:16"

我想要的是

CategoryID  CategoryName    CategoryDescription Commenter   CommentDate
1           Admin           test1               Pino        "2017-04-16 15:47:41"
2           test            bla                 Pino        "2017-04-16 17:17:56"

我尝试了一些不同的东西,但到目前为止还没有运气。

我在这里读过尝试

SELECT a.CategoryID, CategoryName, CategoryDescription, Commenter, CommentDate FROM (
    SELECT ca.CategoryID, ca.CategoryName, ca.CategoryDescription, co.Commenter, co.CommentDate 
    FROM forum_category AS ca 
    JOIN forum_comment AS co 
        ON co.CategoryID = ca.CategoryID
    ORDER BY ca.CategoryID ASC, co.CommentDate DESC
) AS a
ORDER BY a.CategoryID

但这只会导致错误的日期

CategoryID  CategoryName    CategoryDescription Commenter   CommentDate
1           Admin           test1               Pino        "2017-04-16 15:25:30"
2           test            bla                 Pino        "2017-04-16 15:56:16"

先感谢MYSQL Ninjas

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT ca.CategoryID, ca.CategoryName, ca.CategoryDescription, co.Commenter, MAX(co.CommentDate) as max_date
FROM forum_category AS ca 
JOIN forum_comment AS co ON co.CategoryID = ca.CategoryID
GROUP BY ca.CategoryID, ca.CategoryName, ca.CategoryDescription, co.Commenter
ORDER BY ca.CategoryID ASC, max_date DESC;