gpt4 book ai didi

MYSQL GROUP BY 未显示正确的日期

转载 作者:行者123 更新时间:2023-11-29 10:52:51 25 4
gpt4 key购买 nike

我在 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

最佳答案

试试这个:

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;

关于MYSQL GROUP BY 未显示正确的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43441377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com