Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

php - 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.

Example data:
16:56:41 01/14/21 GMT

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.

question from:https://stackoverflow.com/questions/65901856/filter-mysql-query-by-datetime-stored-as-varchar

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your use of STR_TO_DATE is correct, but your date literals are off. 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. Note that we don't need to even include the H:M:S components and can just use date literals.

It would be best to make your datetime column a proper datetime type column, rather than text. This would avoid the need to use STR_TO_DATE.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...