简体   繁体   English

过滤在mysql中存储为varchar的日期

[英]Filter dates stored as varchar in mysql

I am working with a MySQL database where dates are stored as varchar like this: 我正在使用将日期存储为varchar的MySQL数据库,如下所示:

'2013-01-31' in column cl_223 cl_223列中的'2013-01-31'

I need to select only records from 2013 so I tried: 我只需要选择2013年的记录,就可以尝试:

SELECT ..
FROM ....

Where cl_223 Like '2013'   

But that does not seem to work. 但这似乎不起作用。

Thanks for all help! 感谢所有帮助!

You must add % as a wildcard : 您必须将%添加为通配符:

SELECT ..
FROM ....

WHERE cl_223 LIKE '2013%'   

Storing a datettime value in a varchar column complicates some functionality on date time operations. 在varchar列中存储datettime值会使日期时间操作的某些功能复杂化。 But of course you can select your values writing such a query as follow 但是当然您可以选择编写如下查询的值

SELECT * FROM table_name WHERE cl_223 LIKE '2013%'

But if you don't have any performance issue you can convert the varchar column to a datetime value and write stronger typed query like this: 但是,如果您没有任何性能问题,可以将varchar列转换为datetime值,并编写如下更强类型的查询:

  SELECT * FROM table_name WHERE  STR_TO_DATE(cl_223,'%Y-%m-%d2') BETWEEN '2013-01-01' AND '2013-12-31'

But if you need a date time value as a date time in your process you'd better store it in a datetime column instead of a varchar column. 但是,如果您需要一个日期时间值作为流程中的日期时间,则最好将其存储在datetime列而不是varchar列中。

The query should be 查询应该是

SELECT ..
FROM ....

Where cl_223 Like '2013%'

However, the better solution would be to store the dates as DATE data types. 但是,更好的解决方案是将日期存储为DATE数据类型。 If the dates in that column are always used in the format they're in now, the change would be backwards compatible. 如果该列中的日期始终以现在使用的格式使用,则该更改将向后兼容。 It would also allow for easier processing of the date values. 它还可以简化日期值的处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM