首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据DB值限制返回结果

根据DB值限制返回结果
EN

Stack Overflow用户
提问于 2021-03-18 01:12:03
回答 1查看 51关注 0票数 1

我有两个表、类别和故事。

Stories表包含按类别组织的内容。

代码语言:javascript
复制
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)

因此结果应该如下所示:

代码语言:javascript
复制
"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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-18 01:52:35

下面是一个使用窗口函数的解决方案:

代码语言:javascript
复制
with cte as ( 
  select *, row_number() over (partition by c.categories_id order by s.stories_id) as rownum 
  from Categories as c join Stories as s using (categories_id) 
) select * from cte where rownum <= category_story_count;

+---------------+---------------+----------------------+------------+------------+---------------+--------------+--------+
| categories_id | category_name | category_story_count | stories_id | story_name | story_content | story_active | rownum |
+---------------+---------------+----------------------+------------+------------+---------------+--------------+--------+
|             1 | new           |                    2 |          1 | Tax Hike   | blah blah     |            1 |      1 |
|             1 | new           |                    2 |          2 | Tax Cuts   | blah blah     |            1 |      2 |
|             2 | funnies       |                    3 |          4 | Peanuts    | blah blah     |            1 |      1 |
|             2 | funnies       |                    3 |          5 | Garfield   | blah blah     |            1 |      2 |
|             2 | funnies       |                    3 |          6 | Archie     | blah blah     |            1 |      3 |
+---------------+---------------+----------------------+------------+------------+---------------+--------------+--------+

已在MySQL 8.0.23上测试。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66677987

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档