[英]SQL get count of all rows that have the same id
我有一個名為story_comment的表,帶有(整數)列Story_id和comment_id。 我想知道每個故事有多少評論,但我不確定編寫sql查詢的最佳方法。
查詢應返回一個表,其中包含story_id和num_comments列(其中,num_comments是story_comment中的行數,其中story_id與該結果行中的story_id相同)。
所需結果(示例):
story_id | num_comments
4 | 17
6 | 0
7 | 4
我可以通過查詢為一個特定的story_id執行此操作:
SELECT story_id, Count(story_id) as num_comments FROM story_comment where story_id=20;
但我不確定如何對表格中的每個story_id執行此操作。 旁注,我將使用php中的mysqli進行此查詢。
使用GROUP BY
SELECT story_id, Count(story_id) as num_comments FROM story_comment
GROUP BY story_id
GROUP BY語句與聚合函數結合使用,以按一個或多個列對結果集進行分組。
為了讓喜歡聚集函數count()
適用於列的每個獨特的價值而不是完整的表格,新增group by
SELECT story_id, Count(*) as num_comments
FROM story_comment
group by story_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.