搜索以 varchar 形式存储在 MySQL 中的日期之间的值?
您可以使用 STR_TO_DATE() 搜索以 varchar 形式存储的日期之间的值。其语法如下 −
select *from yourTableName where STR_TO_DATE(LEFT(yourColumnName,LOCATE('',yourColumnName)),'%m/%d/%Y') BETWEEN 'yourDateValue1' AND 'yourDateValue2’;
为了理解上述语法,让我们创建一个表。创建表的查询如下 −
mysql> create table SearchDateAsVarchar -> ( -> Id int NOT NULL AUTO_INCREMENT, -> ShippingDate varchar(100), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.99 sec)
使用 INSERT 命令在表中插入一些记录。查询如下 −
mysql> insert into SearchDateAsVarchar(ShippingDate) values('6/28/2011 9:58 AM'); Query OK, 1 row affected (0.19 sec) mysql> insert into SearchDateAsVarchar(ShippingDate) values('6/18/2011 10:50:39 AM'); Query OK, 1 row affected (0.55 sec) mysql> insert into SearchDateAsVarchar(ShippingDate) values('6/22/2011 11:45:40 AM'); Query OK, 1 row affected (0.18 sec)
使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from SearchDateAsVarchar;
以下是输出 −
+----+-----------------------+ | Id | ShippingDate | +----+-----------------------+ | 1 | 6/28/2011 9:58 AM | | 2 | 6/18/2011 10:50:39 AM | | 3 | 6/22/2011 11:45:40 AM | +----+-----------------------+ 3 rows in set (0.00 sec)
以下是可以搜索以 varchar 形式存储的日期之间的值的查询 −
mysql> select *from SearchDateAsVarchar where STR_TO_DATE(LEFT(ShippingDate,LOCATE(' ',ShippingDate)),'%m/%d/%Y') BETWEEN '2011-06-20' AND '2011-06-28';
以下是输出 −
+----+-----------------------+ | Id | ShippingDate | +----+-----------------------+ | 1 | 6/28/2011 9:58 AM | | 3 | 6/22/2011 11:45:40 AM | +----+-----------------------+ 2 rows in set (0.00 sec)
广告