如何使这个 Mysql 查询工作?

发布于 2024-09-19 11:11:58 字数 281 浏览 13 评论 0原文

我的查询:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

悟红尘 2024-09-26 11:11:58

MySQL 不支持分析函数,而这正是您真正想要的:

SELECT x.*
  FROM (SELECT ft.*,
               CASE 
                  WHEN @cat_id = ft.cat_id THEN @rownum := @rownum + 1
                  ELSE @rownum := 1
               END AS rank,
               @cat_id = ft.cat_id
          FROM FORUM_TOPICS ft
          JOIN (SELECT @rownum := 0, @cat_id := -1) r
      ORDER BY ft.cat_id, ft.last_message DESC)
 WHERE x.rank = 1

这将提供一个名为“rank”的计算列,其中基于 last_message 列的最新行将具有该值每个 cat_id 值“1”。外部查询仅获取排名值为 1 的记录...

MySQL doesn't have analytical function support, which is what you're really after:

SELECT x.*
  FROM (SELECT ft.*,
               CASE 
                  WHEN @cat_id = ft.cat_id THEN @rownum := @rownum + 1
                  ELSE @rownum := 1
               END AS rank,
               @cat_id = ft.cat_id
          FROM FORUM_TOPICS ft
          JOIN (SELECT @rownum := 0, @cat_id := -1) r
      ORDER BY ft.cat_id, ft.last_message DESC)
 WHERE x.rank = 1

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" per cat_id value. The outer query only gets the records whose rank value is one...

月下伊人醉 2024-09-26 11:11:58

你的问题有点令人困惑,但我认为你正在寻找这个。

SELECT * FROM forum_topics WHERE cat_id IN(1,2,3,4,5,6,7) group by cat_id order by max(last_message) LIMIT 7

Your question is kind of confusing, but I think you are looking for this.

SELECT * FROM forum_topics WHERE cat_id IN(1,2,3,4,5,6,7) group by cat_id order by max(last_message) LIMIT 7
会傲 2024-09-26 11:11:58

添加一个 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文