如何使这个 Mysql 查询工作?
我的查询:
SELECT *
FROM forum_topics
WHERE cat_id IN(1,2,3,4,5,6,7)
ORDER BY last_message DESC
LIMIT 7
我想获取每个 cat_id 中最大且仅有的一个值(总共 7 个值)。如果可能的话,如何更正此查询以使其正常工作?
有论坛主题,每个主题都有值last_message
,我想获取最新主题的消息时间。希望它是清楚的。
谢谢
My query:
SELECT *
FROM forum_topics
WHERE cat_id IN(1,2,3,4,5,6,7)
ORDER BY last_message DESC
LIMIT 7
I want to get the biggest and only one value of each cat_id (7 values total). How to correct this query to make it work if it's even possible?
There is forum topics and each has value last_message
and I want to get the latest topic's message's time. Hope it's clear.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
MySQL 不支持分析函数,而这正是您真正想要的:
这将提供一个名为“rank”的计算列,其中基于
last_message
列的最新行将具有该值每个cat_id
值“1”。外部查询仅获取排名值为 1 的记录...MySQL doesn't have analytical function support, which is what you're really after:
This will provide a computed column called "rank", where the most recent row based on the
last_message
column will have the value of "1" percat_id
value. The outer query only gets the records whose rank value is one...你的问题有点令人困惑,但我认为你正在寻找这个。
Your question is kind of confusing, but I think you are looking for this.
添加一个 group by 子句,例如
GROUP BY cat_id
这样你的查询将变成
SELECT *
来自论坛主题
WHERE cat_id IN(1,2,3,4,5,6,7)
按 cat_id 分组
按最后一条消息 DESC 排序
限制 7
add a group by clause like
GROUP BY cat_id
So your query will become
SELECT *
FROM forum_topics
WHERE cat_id IN(1,2,3,4,5,6,7)
GROUP BY cat_id
ORDER BY last_message DESC
LIMIT 7