我的 column
包含这样的数据,
07/2002
05/2005
04/2000
month/year
我可以使用查询过滤掉数据吗,即
SELECT * FROM `table` WHERE `fr` < '07/2002'
它应该返回 04/2000
无法使用 MySQL
或者我必须使用其他语言来选择和过滤数据,例如 PHP
?
最佳答案
计划
- use str_to_date to convert the start of month values to dates and compare
查询
select *
from `table`
where str_to_date(concat('01/', fr), '%d/%m/%Y')
<
str_to_date('01/07/2002', '%d/%m/%Y')
;
输出
+---------+
| fr |
+---------+
| 04/2000 |
+---------+
注意
虽然以上是所问问题的解决方案,但它只是处理症状而不是根本问题。
真正的问题是用于存储日期信息的存储类型 考虑使用实际日期来存储此信息。这会导致以下症状:
症状
- complexity : we have to perform further manipulations to transform into the date type we can use
- performance ( see above )
- maintenance ( see this question )
我们可以解决这个问题,因为它是由更改存储类型以正确反射(reflect)语义内容(它的日期信息并且应该能够以这种方式简单地进行比较)引起的
修复
alter table `table` add column fr_datetype date not null;
update `table`
set fr_datetype = str_to_date(concat('01/', fr), '%d/%m/%Y')
;
-- test conversion to date type
select
'error converting' as test_conversion
from `table`
where concat(lpad(extract(month from fr_datetype), 2, '0'), '/', extract(year from fr_datetype)) <> fr
;
-- only finalise this based on successful completion of above select ( no rows returned )
alter table `table` drop column fr;
alter table `table` change column fr_datetype fr date not null;
简化的解决方案
select *
from `table`
where fr < '2002-07-01'
;
关于php - 按日期过滤数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32163576/