PostgreSQL从一个表中选择all并从表关系中连接计数

时间:2014-11-11 22:56:03

标签: sql postgresql join count psql

我有两个表,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, count(*)

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

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

非常感谢您的帮助:D

2 个答案:

答案 0 :(得分:8)

您可以使用包含每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

答案 1 :(得分:4)

select post_categories.id, post_categories.name , count(posts.id)  
from post_categories 
inner join posts 
on post_category_id  =  post_categories.id  
group by post_categories.id, post_categories.name