选择查询以显示具有最大日期的重复值
mysqlmysqli database更新于 2025/6/12 10:52:17
为此,使用 GROUP BY 和 HAVING。让我们首先创建一个表 −
mysql> create table DemoTable ( StudentName varchar(100), DueDate date ); Query OK, 0 rows affected (0.72 sec)
示例
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('John','2019-01-11');
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values('Chris','2019-02-11');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values('Chris','2019-03-11');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('John','2019-04-11');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Bob','2019-05-11');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Bob','2019-06-11');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Robert','2019-07-11');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('Robert','2019-08-11');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Robert','2019-09-11');
Query OK, 1 row affected (0.15 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
输出
+-------------+------------+ | StudentName | DueDate | +-------------+------------+ | John | 2019-01-11 | | Chris | 2019-02-11 | | Chris | 2019-03-11 | | John | 2019-04-11 | | Bob | 2019-05-11 | | Bob | 2019-06-11 | | Robert | 2019-07-11 | | Robert | 2019-08-11 | | Robert | 2019-09-11 | +-------------+------------+ 9 rows in set (0.00 sec)
以下是显示具有最大日期的重复值的查询 −
mysql> select tbl.StudentName,max(tbl.DueDate) from DemoTable tbl group by tbl.StudentName having count(*) > 1;
输出
+-------------+------------------+ | StudentName | max(tbl.DueDate) | +-------------+------------------+ | John | 2019-04-11 | | Chris | 2019-03-11 | | Bob | 2019-06-11 | | Robert | 2019-09-11 | +-------------+------------------+ 4 rows in set (0.00 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

