如何提取 MySQL 日期中的月份和年份并进行比较?
如何从 mySQL 日期中提取月份和日期并将其与另一个日期进行比较?
我找到了 this MONTH() 但它只获取月份。我寻找月份和年份。
How do I extract the month and date from a mySQL date and compare it to another date?
I found this MONTH() but it only gets the month. I looking for month and year.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在Mysql Doku中:
http://dev.mysql.com /doc/refman/5.5/en/date-and-time-functions.html#function_extract
in Mysql Doku:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_extract
虽然评论中对此进行了讨论,但还没有包含它的答案,因此很容易错过。
DATE_FORMAT 工作得非常好,并且可以灵活地处理许多不同的模式。
要将其放入查询中:
While it was discussed in the comments, there isn't an answer containing it yet, so it can be easy to miss.
DATE_FORMAT works really well and is flexible to handle many different patterns.
To put it in a query:
如果您要比较日期,请提取完整日期进行比较。如果您仅比较年份和月份,请使用
If you are comparing between dates, extract the full date for comparison. If you are comparing the years and months only, use
您可能想查看有关日期函数的 mySQL 文档。 http://dev.mysql.com/doc /refman/5.5/en/date-and-time-functions.html
就像有 MONTH() 函数一样,也有 YEAR() 函数。如果您要进行比较,是否有理由缩短日期?您真的有兴趣忽略基于日期的差异吗?如果是的话,这就是您想要的方式吗?
You may want to check out the mySQL docs in regard to the date functions. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
There is a YEAR() function just as there is a MONTH() function. If you're doing a comparison though is there a reason to chop up the date? Are you truly interested in ignoring day based differences and if so is this how you want to do it?
还应该有一个 YEAR()。
至于比较,您可以比较这些年份和月份的第一天的日期,或者您可以将年/月对转换为适合比较的数字(即更大=更晚)。 (留给读者练习。有关提示,请阅读 ISO 日期格式。)
或者您可以使用多重比较(即先是年份,然后是月份)。
There should also be a YEAR().
As for comparing, you could compare dates that are the first days of those years and months, or you could convert the year/month pair into a number suitable for comparison (i.e. bigger = later). (Exercise left to the reader. For hints, read about the ISO date format.)
Or you could use multiple comparisons (i.e. years first, then months).
在 MySQL 中,
dateformat()
在这里可以派上用场。例子:
对于示例日期时间为 12-01-2023 的列
'date'
将产生:
12-2023
In MySQL,
dateformat()
could come handy here.Example:
For a column
'date'
with example datetime: 12-01-2023will yield:
12-2023