gpt4 book ai didi

sql - PostgreSQL 从一个表中选择全部并从表关系中加入计数

转载 作者:行者123 更新时间:2023-11-29 11:30:46 24 4
gpt4 key购买 nike

我有两个表,post_categoriesposts。我正在尝试 select * from post_categories;,但还会返回一个临时列,其中包含每次在帖子上使用帖子类别时的计数。

帖子

| id | name | post_category_id |
| 1 | test | 1 |
| 2 | nest | 1 |
| 3 | vest | 2 |
| 4 | zest | 3 |

帖子类别

| id | name  |
| 1 | cat_1 |
| 2 | cat_2 |
| 3 | cat_3 |

基本上,我尝试在没有子查询的情况下使用连接来执行此操作。类似这样的东西,但在真正的 psql 中。

select * from post_categories some-type-of-join posts,计数(*)

理想情况下,结果是这样。

| id | name  | count |
| 1 | cat_1 | 2 |
| 2 | cat_2 | 1 |
| 3 | cat_3 | 1 |

非常感谢您的帮助:D

最佳答案

您可以使用包含每个 post_category_id 计数的派生表,并将其左连接到 post_categories

select p.*, coalesce(t1.p_count,0)
from post_categories p
left join (
select post_category_id, count(*) p_count
from posts
group by post_category_id
) t1 on t1.post_category_id = p.id

关于sql - PostgreSQL 从一个表中选择全部并从表关系中加入计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26876160/

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