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
SQL query where() date's year is $year
提问by simPod
I store dates in my database in a column of date
data type.
我将日期存储在数据库中的date
数据类型列中。
Let's say I have column date
where 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 date
is 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