MySQL如何比较时间(datetime)大小

2022-11-13,,

这篇文章主要介绍了MySQL如何比较时间(datetime)大小,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

目录
  • 比较时间(datetime)大小
  • mysql时间比较 -- date和datetime
    • date 直接比较即可,yyyy-MM-dd
    • create_time 为 datetime时

比较时间(datetime)大小

遇到一个业务功能需要将当前时间与数据库中的会议开始、结束时间进行比较,记录一下,方便下次用。

用unix_timestamp函数,将字符型的时间,转成unix时间戳。

select meeting_id,meeting_name,start_time,end_time from meeting_data 
    where meeting_id REGEXP '[0-9]{4}0001' 
        and unix_timestamp(start_time) < unix_timestamp(NOW()) 
        and unix_timestamp(end_time) > unix_timestamp(NOW());

mysql时间比较 -- date和datetime

date 直接比较即可,yyyy-MM-dd

如上图

date存入数据库类型为 yyyy-MM-dd类型,可以直接进行比较。

datetime 特别注意。虽然写sql使用的是 yyyy-MM-dd 但是mysql默认会添加 00:00:00 作比较。

比如 :

create_time 为 datetime时

以下sql只能获取到 30 号的数据

select * from ok where create_time between ‘2019-01-30' and ‘2019-01-31'

实际查询如下

select * from ok where create_time between ‘2019-01-30 00:00:00' and ‘2019-01-31 00:00:00' .

如果精确为日期 需要使用 date_format 转换函数 进行 格式化 后比较。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持北冥有鱼。

《MySQL如何比较时间(datetime)大小.doc》

下载本文的Word格式文档,以方便收藏与打印。