让我们来看一个获取列中每个不同值的计数的示例。首先,我们将创建一个表。
CREATE命令用于创建表。
mysql> create table DistinctDemo1 - > ( - > id int, - > name varchar(100) - > );
mysql> insert into DistinctDemo1 values(1,'John'); mysql> insert into DistinctDemo1 values(2,'John'); mysql> insert into DistinctDemo1 values(3,'John'); mysql> insert into DistinctDemo1 values(4,'Carol'); mysql> insert into DistinctDemo1 values(5,'David');
mysql> select *from DistinctDemo1;
以下是显示所有记录的输出。
+------+-------+ | id | name | +------+-------+ | 1 | John | | 2 | John | | 3 | John | | 4 | Carol | | 5 | David | +------+-------+ 5 rows in set (0.00 sec)
以下是获取计数的语法。
mysql> SELECT name,COUNT(1) as OccurenceValue FROM DistinctDemo1 GROUP BY name ORDER BY OccurenceValue;
这是输出。
+-------+----------------+ | name | OccurenceValue | +-------+----------------+ | Carol | 1 | | David | 1 | | John | 3 | +-------+----------------+ 3 rows in set (0.04 sec)