How to get the count of each distinct value in a column?

MysqlSqlCount

Mysql Problem Overview


I have an SQL table called "posts" that looks like this:

id | category
-----------------------
1  | 3
2  | 1
3  | 4
4  | 2
5  | 1
6  | 1
7  | 2

Each category number corresponds to a category. How would I go about counting the number of times each category appears on a post all in one SQL query?

As an example, such a query might return a symbolic array such as this: (1:3, 2:2, 3:1, 4:1)

My current method is to use queries for each possible category, such as: SELECT COUNT(*) AS num FROM posts WHERE category=#, and then combine the return values into a final array. However, I'm looking for a solution that uses only one query.

Mysql Solutions


Solution 1 - Mysql

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeff GortmakerView Question on Stackoverflow
Solution 1 - MysqlDan GrossmanView Answer on Stackoverflow