MySQL counts the number of distinct values in a column

https://yiqiwuliao.com/post/mysql/mysqltong-ji-yi-ge-lie-zhong-bu-tong-zhi-de-shu-liang

mySQL Count the number of different values ​​in a column
This requirement is actually very common. For example, we have a user source table to mark the channel from which users signed up. The table structure is as follows...

where origin is the source of users, and the values ​​are iPhone, Android, and Web. Now it is necessary to count the number of users registered by these three channels.
Solution 1

SELECT count(*)
FROM user_operation_log
WHERE origin = 'iPhone';

SELECT count(*)
FROM user_operation_log
WHERE origin = 'Android';

SELECT count(*)
FROM user_operation_log
WHERE origin = 'Web'; count
separately with where statement their respective quantities.
In this way, the amount of query is a bit too much. If there are 10 values, then 10 similar statements have to be written, which is very troublesome.
Is there a single sentence to do it? So I did some research.
Solution 2

We know that count can be used to count not only the number of rows, but also the number of column values, for example:
Count how many rows there are in user_operation_log:
SELECT count(*) FROM user_operation_log
Count the number of origin columns whose value is not NULL:
SELECT count(origin) FROM user_operation_log
So we can use this feature to achieve the above requirements
The first way of writing (implemented with count)

SELECT
  count(origin = 'iPhone' OR NULL) AS iPhone,
  count(origin = 'Android' OR NULL) AS Android,
  count(origin = 'Web' OR NULL) AS Web
FROM user_operation_log; The second way of writing the
query result
search_result
(implemented with sum)

SELECT
  sum(if(origin = 'iPhone', 1, 0)) AS iPhone,
  sum(if(origin = 'Android', 1, 0)) AS Android,
  sum(if(origin = 'Web ', 1, 0)) AS Web
FROM user_operation_log;

SELECT
  sum(origin = 'iPhone')  AS iPhone,
  sum(origin = 'Android') AS Android,
  sum(origin = 'Web')     AS Web
FROM user_operation_log;

第4种,最优的:
SELECT origin,count(*) num FROM user_operation_log GROUP BY origin;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326180880&siteId=291194637