php 获取当前年份和下一个表单 mysql

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4811271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 14:28:16  来源:igfitidea点击:

Get Current year and next form mysql

phpmysql

提问by Tobias

Im am selecting various things from a table. The problem is I only want to select them if they belong to the current year and the next year.

我正在从表格中选择各种东西。问题是我只想选择它们,如果它们属于当年和明年。

My table looks like this

我的桌子看起来像这样

Title Text Date

标题文本日期

The date is formated like this 0000-00-00 and is in the format "date"

日期的格式如下 0000-00-00 并且格式为“日期”

So the question is how can i select only items from only this year and the next?

所以问题是我如何只选择今年和明年的项目?

Example: the year is 2012, I have items in my table that is old and i dont want them to show - I only want to select items from at the first 2012 1 January and last in this case 31 Dec 2013 current year 2012 + 1 year.

示例:年份是 2012,我的表中有旧项目,我不希望它们显示 - 我只想从 2012 年第一个 1 月 1 日和最后一个在这种情况下选择项目 2013 年 12 月 31 日当前年份 2012 + 1年。

Thanks a lot for any help!

非常感谢您的帮助!

回答by Dan Grossman

SELECT 
  * 
FROM 
  table 
WHERE 
  YEAR(date) = YEAR(CURDATE()) 
OR 
  YEAR(date) = YEAR(CURDATE()) + 1

http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html

http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html

回答by Mchl

SELECT 
  *
FROM
  table
WHERE
  date BETWEEN CONCAT(YEAR(CURDATE()),'-01-01') AND CONCAT(YEAR(CURDATE())+1,'-12-31')

As ugly as it looks, it allows your query to use index on datefield.

尽管看起来很丑陋,但它允许您的查询在date字段上使用索引。

Better idea is to create limiting dates in external PHP script, so that the query can use query cache.

更好的想法是在外部 PHP 脚本中创建限制日期,以便查询可以使用查询缓存。



If you only want to show items, that are no older than two years, you can do this:

如果您只想显示不超过两年的项目,您可以这样做:

SELECT
  *
FROM
  table
WHERE
  date >= CURDATE() - INTERVAL 2 YEAR;