【发布时间】:2021-06-15 01:55:42
【问题描述】:
我有两个表,类别和故事。
Stories 表包含按类别组织的内容。
categories_id, category_name, category_story_count
1, news, 2
2, funnies, 3
stories_id, categories_id, story_name, story_content, story_active
1, 1, "Tax Hike", "blah blah", 1
2, 1, "Tax Cuts", "blah blah", 1
2, 1, "Election", "blah blah", 1
4, 2, "Peanuts", "blah blah", 1
5, 2, "Garfield", "blah blah", 1
6, 2, "Archie", "blah blah", 1
我想要一个查询,它将根据 category_story_count 返回每个类别的正确故事数,以及故事是否处于活动状态 (story_active = 1)
所以结果应该是这样的:
"news", "Tax Hike"
"news", "Tax Cuts"
"funnies", "Peanuts"
"funnies", "Garfield"
"funnies", "Archie"
两个“新闻”故事,因为新闻类别 1,category_story_count = 2,三个“有趣”故事,因为有趣 2,所以 category_story_count = 3
我已经尝试过内部连接、嵌套和限制,但无法让它返回我的目标。
任何帮助将不胜感激。
编辑: MySQL版本() 8.0.23
【问题讨论】:
-
你使用什么版本的 MySQL?也就是说,
SELECT VERSION();返回什么?如果您使用 MySQL 8.0,可能会有窗口函数的解决方案。 -
VERSION() 8.0.23
标签: mysql greatest-n-per-group