通过包含日期值的列从单个 MySQL 查询中检索最小和最大日期
为此,你可以使用聚合函数 MIN() 和 MAX()。让我们先创建一个表 −
mysql> create table DemoTable(AdmissionDate date); Query OK, 0 rows affected (0.76 sec)
使用插入命令在表中插入一些记录 −
mysql> insert into DemoTable values('2019-01-21'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('2018-12-31'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values('2016-11-01'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('2019-04-11'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('2016-02-01'); Query OK, 1 row affected (0.28 sec)
使用 select 语句从表中显示所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+---------------+ | AdmissionDate | +---------------+ | 2019-01-21 | | 2018-12-31 | | 2016-11-01 | | 2019-04-11 | | 2016-02-01 | +---------------+ 5 rows in set (0.00 sec)
以下是用于在单个查询中检索最小和最大日期的查询 −
mysql> select MIN(AdmissionDate) AS MinDate,MAX(AdmissionDate) AS MaxDate from DemoTable;
这将产生以下输出 −
+------------+------------+ | MinDate | MaxDate | +------------+------------+ | 2016-02-01 | 2019-04-11 | +------------+------------+ 1 row in set (0.00 sec)
广告