如何使用 MySQL 查询来选择具有特定日期和时间的记录?
你可以使用 MySQL 的 BETWEEN 子句来选择具有特定日期和时间的记录。语法如下。
select *from AllRecordsFromadate where AdmissionDate between 'yourDateTimeValue1 ' and ''yourDateTimeValue2';
为了理解上述语法,我们首先创建一个表。创建表的查询如下。
mysql> create table AllRecordsFromadate -> ( -> Id int, -> Name varchar(100), -> Age int, -> AdmissionDate datetime -> ); Query OK, 0 rows affected (0.53 sec)
使用 insert 命令向表中插入一些记录。插入记录的查询如下。
mysql> insert into AllRecordsFromadate values(101,'John',23,'2018-10-13'); Query OK, 1 row affected (0.18 sec) mysql> insert into AllRecordsFromadate values(102,'Carol',24,'2014-12-5 12:34:50'); Query OK, 1 row affected (0.18 sec) mysql> insert into AllRecordsFromadate values(103,'Mike',25,'2014-12-5 12:30:40'); Query OK, 1 row affected (0.23 sec) mysql> insert into AllRecordsFromadate values(104,'Bob',24,'2015-10-7 11:10:20'); Query OK, 1 row affected (0.20 sec) mysql> insert into AllRecordsFromadate values(105,'Sam',25,'2011-6-26 10:10:20'); Query OK, 1 row affected (0.11 sec)
使用 select 命令显示表中的所有记录。查询如下。
mysql> select *from AllRecordsFromadate;
以下是输出。
+------+-------+------+---------------------+ | Id | Name | Age | AdmissionDate | +------+-------+------+---------------------+ | 101 | John | 23 | 2018-10-13 00:00:00 | | 102 | Carol | 24 | 2014-12-05 12:34:50 | | 103 | Mike | 25 | 2014-12-05 12:30:40 | | 104 | Bob | 24 | 2015-10-07 11:10:20 | | 105 | Sam | 25 | 2011-06-26 10:10:20 | +------+-------+------+---------------------+ 5 rows in set (0.00 sec)
以下查询可用于特定的日期和时间。
mysql> select *from AllRecordsFromadate where AdmissionDate between '2014-12-05 10:00:00' and '2014-12-05 12:50:58';
以下是输出。
+------+-------+------+---------------------+ | Id | Name | Age | AdmissionDate | +------+-------+------+---------------------+ | 102 | Carol | 24 | 2014-12-05 12:34:50 | | 103 | Mike | 25 | 2014-12-05 12:30:40 | +------+-------+------+---------------------+ 2 rows in set (0.00 sec)
广告