mysql 比较日期格式化_与date_format进行mysql日期比较

bd96500e110b49cbb3cd949968f18be7.png

I googled and tried several ways to compare date but unfortunately didn't get the result as expected. I have current state of records like following:

mysql> select date_format(date(starttime),'%d-%m-%Y') from data;

+-----------------------------------------+

| date_format(date(starttime),'%d-%m-%Y') |

+-----------------------------------------+

| 28-10-2012 |

| 02-11-2012 |

| 02-11-2012 |

| 02-11-2012 |

| 03-11-2012 |

| 03-11-2012 |

| 07-11-2012 |

| 07-11-2012 |

I would like to compare date and therefore do like this:

mysql> select date_format(date(starttime),'%d-%m-%Y') from data where date_format(date(starttime),'%d-%m-%y') >= '02-11-2012';

+-----------------------------------------+

| date_format(date(starttime),'%d-%m-%Y') |

+-----------------------------------------+

| 28-10-2012 |

| 02-11-2012 |

| 02-11-2012 |

| 02-11-2012 |

| 03-11-2012 |

| 03-11-2012 |

| 07-11-2012 |

| 07-11-2012 |

I believe that the result should not include '28-10-2012'. Any suggestion? Thanks in advance.

解决方案

Your format is fundamentally not a sortable one to start with - you're comparing strings, and the string "28-10-2012" is greater than "02-11-2012".

Instead, you should be comparing dates as dates, and then only converting them into your target format for output.

Try this:

select date_format(date(starttime),'%d-%m-%Y') from data

where date(starttime) >= date '2012-11-02';

(The input must always be in year-month-value form, as per the documentation.)

Note that if starttime is a DATETIME field, you might want to consider changing the query to avoid repeated conversion. (The optimizer may well be smart enough to avoid it, but it's worth checking.)

select date_format(date(starttime),'%d-%m-%Y') from data

where starttime >= '2012-11-02 00:00:00';

(Note that it's unusual to format a date as d-m-Y to start with - it would be better to use y-M-d in general, being the ISO-8601 standard etc. However, the above code does what you asked for in the question.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值