sql - PostgreSQL select all from one table and join count from table relation -
sql - PostgreSQL select all from one table and join count from table relation -
i have 2 tables, post_categories
, posts
. i'm trying select * post_categories;
, homecoming temporary column count each time post category used on post.
posts
| id | name | post_category_id | | 1 | test | 1 | | 2 | nest | 1 | | 3 | vest | 2 | | 4 | zest | 3 |
post categories
| id | name | | 1 | cat_1 | | 2 | cat_2 | | 3 | cat_3 |
basically, i'm trying without subqueries , joins instead. this, in real psql
.
select * post_categories some-type-of-join posts, count(*)
resulting in this, ideally.
| id | name | count | | 1 | cat_1 | 2 | | 2 | cat_2 | 1 | | 3 | cat_3 | 1 |
your help appreciated :d
you can utilize derived table contains counts per post_category_id
, left bring together post_categories
table
select p.*, coalesce(t1.p_count,0) post_categories p left bring together ( select post_category_id, count(*) p_count posts grouping post_category_id ) t1 on t1.post_category_id = p.id
sql postgresql join count psql
Comments
Post a Comment