MySQL 查询获取列中不同记录的数量

mysqlmysqli database更新于 2023/11/26 18:05:00

要获取不同记录的数量,请使用 DISTINCT 和 COUNT()。语法如下 −

select count(DISTINCT yourColumnName) from yourTableName;

首先我们创建一个表 −

mysql> create table DemoTable
-> (
-> Name varchar(20),
-> Score int
-> );
Query OK, 0 rows affected (0.67 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable values('John',56);
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable values('Sam',89);
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values('John',56);
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable values('Carol',60);
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values('Sam',89);
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('Carol',60);
Query OK, 1 row affected (0.20 sec)

使用 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)

相关文章