php - 按日期过滤数据?

标签 php mysql mysqli

我的 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 |
+---------+

sqlfiddle


注意

虽然以上是所问问题的解决方案,但它只是处理症状而不是根本问题。

真正的问题是用于存储日期信息的存储类型 考虑使用实际日期来存储此信息。这会导致以下症状:

症状

  • 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/

相关文章:

php - 加入多个表和搜索参数

java - MySQL (Java) 中的 str_to_date 错误

PHP MySQL 从两个表中选择数据并按第三个表中的字段排序

php - 为什么数据没有插入数据库?

php 和 mysql 最先进的...哪个扩展?

php - 如何在不使用链接的情况下更改 $_GET 变量的值?

php - 需要在HTML表格中以特定格式显示mysql表数据

javascript - 我的接收器如何输入消息并显示在我的浏览器上

mysql - 创建在插入期间用默认值替换 '-' 的表

php - 使用 PHP 创建电子邮件列表