简体   繁体   English

SQL - 如何 select 日期从过去 5 年开始,包括最早年份的 1 月 1 日

[英]SQL - How to select date from the past 5 years to include 1st of Jan of the oldest year

I am trying to select data entered for the past 5 years (to start from the 1st of Jan of the first or oldest year).我正在尝试输入过去 5 年的 select 数据(从第一年或最早年份的 1 月 1 日开始)。 I've constructed the query below but it does not begin from the 1st of January of the oldest year.我已经构建了下面的查询,但它不是从最早年份的 1 月 1 日开始的。

SELECT col_name FROM table_name WHERE entry_date > curdate() - interval (dayofmonth(curdate()) - 1) day - interval 5 year

Any help would be appreciated.任何帮助,将不胜感激。

You seem to be using MySQL.您似乎正在使用 MySQL。 The simplest method is going to be:最简单的方法是:

SELECT col_name
FROM table_name
WHERE YEAR(entry_date) >= YEAR(curdate()) - 5;

Note that the use of YEAR() is not index-friendly.请注意, YEAR()的使用对索引不友好。 However, selecting five years worth of data is probably not going to benefit from an index anyway.但是,无论如何选择价值五年的数据可能不会从索引中受益。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM