MySQL 如何实现MAX(distinct…)?不使用DISTINCT有什么区别

MySQL 如何实现MAX(distinct…)?不使用DISTINCT有什么区别

让我们先看一下使用MAX()中的DISTINCT的第一个语法 –

select max(DISTINCT yourColumnName) from yourTableName;

第二个语法如下,它没有使用DISTINCT –

select max( yourColumnName) from yourTableName;

注意 - 上述两个查询使用DISTINCT关键字或不使用都会得到相同的结果。 MySQL内部将MAX(yourColumnName)转换为DISTINCT关键字。

现在让我们看一个例子并创建一个表 –

mysql> create table DemoTable
(
   Number int
);
Query OK, 0 rows affected (1.50 sec)

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

mysql> insert into DemoTable values(80);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(88);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(78);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(88);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(68);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(88);
Query OK, 1 row affected (0.10 sec)

使用select语句显示表中的所有记录 –

mysql> select *from DemoTable;

将会产生以下输出 –

+--------+
| Number |
+--------+
|     80 |
|     88 |
|     78 |
|     88 |
|     68 |
|     88 |
+--------+
6 rows in set (0.00 sec)

情况1 - 下面是实现MAX(DISTINCT ..)的查询 –

mysql> select max(DISTINCT Number) from DemoTable;

将会产生以下输出 –

+----------------------+
| max(DISTINCT Number) |
+----------------------+
|                   88 |
+----------------------+
1 row in set (0.00 sec)

情况2 - 下面是实现没有DISTINCT的MAX()的查询 –

mysql> select max(Number) from DemoTable;

将会产生以下输出 –

+-------------+
| max(Number) |
+-------------+
|          88 |
+-------------+
1 row in set (0.07 sec)

如上所述,两者均给出相同的结果。

阅读更多:MySQL 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程