MySQL 如何计算不同的值

MySQL 如何计算不同的值

要计算不同的值,可以在聚合函数 count() 中使用 distinct。

语法如下 −

select count(distinct yourColumnName) as anyVariableName from yourTableName;

要理解上述概念,我们先创建一张表。以下是创建表的查询语句 −

mysql> create table DistinctDemo
   −> (
   −> Name varchar(200)
   −> );
Query OK, 0 rows affected (0.58 sec)

对于我们的示例,让我们在表中插入重复的记录。插入记录的查询语句如下 −

mysql> insert into DistinctDemo values('John');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DistinctDemo values('Sam');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DistinctDemo values('John');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DistinctDemo values('Johnson');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DistinctDemo values('John');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DistinctDemo values('Johnson');
Query OK, 1 row affected (0.12 sec)

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

mysql> insert into DistinctDemo values('Johnson');
Query OK, 1 row affected (0.10 sec)

使用 select 语句显示所有记录。查询显示所有记录的语句如下 −

mysql> select *from DistinctDemo;

以下是显示一些重复记录的输出−

+---------+
| Name    |
+---------+
| John    |
| Sam     |
| John    |
| Johnson |
| John    |
| Johnson |
| Sam     |
| Johnson |
+---------+
8 rows in set (0.00 sec)

以下是用于从表中计算不同值的查询 −

mysql> select count(distinct Name) as DistinctValues from DistinctDemo;

以下是输出结果−

+----------------+
| DistinctValues |
+----------------+
|              3 |
+----------------+
1 row in set (0.01 sec)

结果 i3 告诉我们表中有 3 个不同的值。

阅读更多:MySQL 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程