简体   繁体   中英

postgresql: Need a sql query to find how many posts are there with one category

\\d posts

                                   Table "public.posts"
   Column    |          Type          |                     Modifiers                      
-------------+------------------------+----------------------------------------------------
 id          | integer                | not null default nextval('posts_id_seq'::regclass)
 title       | character varying(100) | not null
 content     | character varying(500) | not null
 created_at  | date                   | 
 updated_at  | date                   | 
 tags        | character varying(55)  | not null default '50'::character varying
 category_id | integer                | not null default 1
Indexes:
    "posts_pkey" PRIMARY KEY, btree (id)

\\d categories

                                    Table "public.categories"
    Column     |         Type          |                        Modifiers                        
---------------+-----------------------+---------------------------------------------------------
 id            | integer               | not null default nextval('categories_id_seq'::regclass)
 category_name | character varying(50) | not null
 created_at    | date                  | 
 updated_at    | date                  | 
Indexes:
    "categories_pkey" PRIMARY KEY, btree (id)

Need to count and get how many posts are there for one category. How can i do this?

SELECT c.id, c.category_name, COUNT(p.id)
   FROM public.categories c
       LEFT JOIN public.posts p
           ON c.id = p.category_id
   GROUP BY c.id, c.category_name
SELECT category_id, count(*) AS ct
FROM   posts
WHERE  category_id = $search_cat_id
GROUP  BY 1
SELECT c.category_name, count(p.id) as NumberOfPosts
FROM public.posts p
LEFT JOIN public.categories c ON (p.category_id = c.id)
GROUP BY c.category_name

To address the follow up question in the comment, you can filter the 0 counts using a nested query:

SELECT * 
FROM (
    SELECT c.category_name, count(p.id) as NumberOfPosts
    FROM public.posts p
    LEFT JOIN public.categories c ON (p.category_id = c.id)
    GROUP BY c.category_name
) as countedPosts
WHERE countedPosts.NumberOfPosts > 0

For one category:

select count(*) from posts where category_id=YOUCATEGORY;

For all categories

select c.category_name, count(*) from posts p, categories c where p.category_id = c.id group by c.id having count(*) != 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM