获取 MySQL 列中仅唯一行的数量?


在 MySQL 中,COUNT() 会显示行数。DISTINCT 用于忽略重复行并仅获取唯一行的数量。

让我们首先创建一个表

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(10)
);
Query OK, 0 rows affected (0.47 sec)

以下是使用 insert 命令在表中插入一些记录的查询

mysql> insert into DemoTable(FirstName) values('Larry');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(FirstName) values('Sam');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(FirstName) values('Larry');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(FirstName) values('Mike');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(FirstName) values('Robert');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(FirstName) values('Carol');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(FirstName) values('Mike');
Query OK, 1 row affected (0.12 sec)

以下是使用 select 命令从表中显示记录的查询

mysql> select *from DemoTable;

这将生成以下输出

+----+-----------+
| Id | FirstName |
+----+-----------+
|  1 | Larry     |
|  2 | John      |
|  3 | Sam       |
|  4 | John      |
|  5 | John      |
|  6 | Larry     |
|  7 | Mike      |
|  8 | Robert    |
|  9 | Carol     |
| 10 | Mike      |
+----+-----------+
10 rows in set (0.00 sec)

以下是忽略 COUNT 中的重复行并仅获取唯一行数量的查询

mysql> select count(distinct FirstName) from DemoTable;

这将生成以下输出

+---------------------------+
| count(distinct FirstName) |
+---------------------------+
|                         6 |
+---------------------------+
1 row in set (0.03 sec)

更新于: 2019-07-30

152 次浏览

开启你的 职业生涯

通过完成课程获取认证

开始学习
广告