php SQL 查询 where() 日期的年份是 $year

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9186741/
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-26 06:19:32  来源:igfitidea点击:

SQL query where() date's year is $year

phpsql

提问by simPod

I store dates in my database in a column of datedata type.

我将日期存储在数据库中的date数据类型列中。

Let's say I have column datewhere I store data like this "2011-01-01", "2012-01-01", "2012-02-02" etc.

假设我有一列date存储数据,如“2011-01-01”、“2012-01-01”、“2012-02-02”等。

Now I need to make SQL that selects only rows where dateis equal to 2012

现在我需要使 SQL 只选择date等于的行2012

SELECT * FROM table WHERE date=hasSomehowYearEqualTo=2012

SELECT * FROM table WHERE date=hasSomehowYearEqualTo=2012

What would be the query like?

查询会是什么样的?

回答by Eugen Rieck

Do NOTuse YEAR(date)- this will calculate YEAR(date)for all dates, even for those, you never use. It will also make use of an index impossible - worst case on the DB layer.

千万不要使用YEAR(date)-这将计算YEAR(date)所有日期,即使对于那些,你永远不会使用。它还将使用不可能的索引 - 在 DB 层上的最坏情况。

Use

$sql="SELECT * FROM table WHERE `date` BETWEEN '$year-01-01' AND '$year-12-31'"

As a general rule: If you have the choice between a calculation on a constant and a calculation on a field, use the former.

作为一般规则:如果您可以在常量计算和字段计算之间进行选择,请使用前者。

回答by Gabriele Petrioli

Check out the YEAR()docsfunction for MySQL

查看MySQL的YEAR()docs函数

SELECT * FROM table WHERE YEAR(date)=2012

回答by user868322

select * from table where DATEPART(YEAR,[DATE])=2012

select * from table where DATEPART(YEAR,[DATE])=2012