要获取不同记录的计数,请使用DISTINCT和COUNT()
。以下是语法-
select count(DISTINCT yourColumnName) from yourTableName;
让我们首先创建一个表-
mysql> create table DemoTable -> ( -> Name varchar(20), -> Score int -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('John',56); mysql> insert into DemoTable values('Sam',89); mysql> insert into DemoTable values('John',56); mysql> insert into DemoTable values('Carol',60); mysql> insert into DemoTable values('Sam',89); mysql> insert into DemoTable values('Carol',60);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable
输出结果
这将产生以下输出-
+-------+-------+ | Name | Score | +-------+-------+ | John | 56 | | Sam | 89 | | John | 56 | | Carol | 60 | | Sam | 89 | | Carol | 60 | +-------+-------+ 6 rows in set (0.00 sec)
这是获取列中不同记录计数的查询-
mysql> select count(DISTINCT Score) from DemoTable;
输出结果
这将产生以下输出-
+-----------------------+ | count(DISTINCT Score) | +-----------------------+ | 3 | +-----------------------+ 1 row in set (0.00 sec)