[英]Filter MySQL Query By DateTime Stored As Varchar
I'm trying to filter a MySQL query by a field that stores datetime values, but uses a varchar data type.我正在尝试通过存储日期时间值但使用 varchar 数据类型的字段过滤 MySQL 查询。
Example data:示例数据:
16:56:41 01/14/21 GMT格林威治标准时间 21 年 1 月 14 日 16:56:41
Example code:示例代码:
SELECT * FROM table_name WHERE STR_TO_DATE(datetime,'%H:%i:%S %m/%d/%y') BETWEEN '00:00:00 01/14/21' AND '23:59:59 01/14/21'"
The query is currently returning nothing at all.该查询当前根本没有返回任何内容。 However the code below works:
但是下面的代码有效:
SELECT * FROM table_name
Any thoughts would be much appreciated.任何想法将不胜感激。
Your use of STR_TO_DATE
is correct, but your date literals are off.您对
STR_TO_DATE
的使用是正确的,但您的日期文字已关闭。 Fix them, and your query should work:修复它们,您的查询应该可以工作:
SELECT *
FROM table_name
WHERE STR_TO_DATE(datetime,'%H:%i:%S %m/%d/%y') >= '2021-01-14' AND
STR_TO_DATE(datetime,'%H:%i:%S %m/%d/%y') < '2021-01-15';
The above assumes that you want records occurring on 14th January, 2021, proper.以上假设您希望记录发生在 2021 年 1 月 14 日,正确。 Note that we don't need to even include the H:M:S components and can just use date literals.
请注意,我们甚至不需要包含 H:M:S 组件,只需使用日期文字即可。
It would be best to make your datetime
column a proper datetime type column, rather than text.最好使您的
datetime
时间列成为正确的日期时间类型列,而不是文本。 This would avoid the need to use STR_TO_DATE
.这将避免使用
STR_TO_DATE
的需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.