简体   繁体   中英

SQL get count of all rows that have the same id

I have a table called story_comment with (integer) columns story_id, and comment_id. I want to know how many comments each story has but I'm not sure the best way to write the sql query.

The query should return a table with the columns story_id and num_comments (where num_comments is the number of rows in story_comment where story_id is the same as the story_id in that results row).

Desired Results (Example):

story_id | num_comments

   4  |            17
   6  |             0
   7  |             4

I was able to do this for one particular story_id with the query:

SELECT story_id, Count(story_id) as num_comments FROM story_comment where story_id=20;

but I'm not sure how I can do this for every story_id in the table. Side note I'm going to be doing this query using mysqli in php.

Use GROUP BY

SELECT story_id, Count(story_id) as num_comments FROM story_comment  
GROUP BY story_id

The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.

To make aggregate functions like count() apply to each unique value of a column instead to the complete table, add a group by

SELECT story_id, Count(*) as num_comments 
FROM story_comment
group by story_id

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