比较DATE字符串和MySQL DATETIME字段中的字符串?
您可以借助DATE()
MySQL中的函数将DATE字符串与DATETIME字段中的字符串进行比较。语法如下-
select *from yourTableName where DATE(yourColumnName) = ’anyDateString’;
为了理解上述语法,让我们创建一个表并在该表中设置一些日期时间值。创建表的查询-
mysql> create table DateTimeDemo −> ( −> ArrivalTime datetime −> );
让我们借助insert命令在表中插入一些记录。以下是插入记录的查询-
mysql> insert into DateTimeDemo values(now()); mysql> insert into DateTimeDemo values(date_add(now(),interval 2 year)); mysql> insert into DateTimeDemo values(date_add(now(),interval 1 year)); mysql> insert into DateTimeDemo values(date_add(now(),interval 4 year)); mysql> insert into DateTimeDemo values(date_add(now(),interval -2 year)); mysql> insert into DateTimeDemo values(date_add(now(),interval -1 year));
在select语句的帮助下显示所有记录。查询以显示表中的所有记录-
mysql> select *from DateTimeDemo;
以下是输出-
+---------------------+ | ArrivalTime | +---------------------+ | 2018-12-06 10:12:45 | | 2020-12-06 10:13:10 | | 2019-12-06 10:13:21 | | 2022-12-06 10:13:27 | | 2016-12-06 10:13:42 | | 2017-12-06 10:13:50 | +---------------------+ 6 rows in set (0.00 sec)
现在,实现上面讨论的用于将字符串与日期时间字段进行比较的语法。查询如下-
mysql> select *from DateTimeDemo where date(ArrivalTime) = '2022-12-06';
以下是输出-
+---------------------+ | ArrivalTime | +---------------------+ | 2022-12-06 10:13:27 | +---------------------+ 1 row in set (0.14 sec)