我们可以忽略 COUNT 中的重复行吗?
mysqlmysqli database
是的,我们可以使用 DISTINCT 忽略 COUNT 中的重复行。以下是语法:
select count(distinct yourColumnName) from yourTableName;
在 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)