寻找表格中最近的3个日期的MySQL查询,并且结果的日期不应重复
要查找最新的日期,按DESC顺序对日期记录进行排序。由于我们只想获取3个日期,因此使用LIMIT 3。
我们先创建一个表格——
mysql> create table DemoTable ( AdmissionDate date ); Query OK, 0 rows affected (0.56 sec)
使用insert命令在表格中插入一些记录——
mysql> insert into DemoTable values('2019-09-04'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values('2019-08-10'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('2019-09-21'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('2019-09-18'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('2019-09-21'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable values('2019-08-18'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('2019-09-18'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values('2019-09-16'); Query OK, 1 row affected (0.10 sec)
使用select语句显示表格中的所有记录——
mysql> select *from DemoTable;
这将生成以下输出——
+---------------+ | AdmissionDate | +---------------+ | 2019-09-04 | | 2019-08-10 | | 2019-09-21 | | 2019-09-18 | | 2019-09-21 | | 2019-08-18 | | 2019-09-18 | | 2019-09-16 | +---------------+ 8 rows in set (0.00 sec)
以下是查询表格中最近3个日期的代码——
mysql> select AdmissionDate from (select distinct AdmissionDate from DemoTable) tbl order by AdmissionDate desc limit 3;
这将生成以下输出——
+---------------+ | AdmissionDate | +---------------+ | 2019-09-21 | | 2019-09-18 | | 2019-09-16 | +---------------+ 3 rows in set (0.00 sec)
广告