Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Current year and next form mysql

Tags:

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"

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.

Thanks a lot for any help!

like image 750
Tobias Avatar asked Jan 26 '11 23:01

Tobias


People also ask

How do I get this year data in MySQL?

Use the YEAR() function to retrieve the year value from a date/datetime/timestamp column in MySQL. This function takes only one argument – a date or date and time. This can be the name of a date/datetime/timestamp column or an expression returning one of those data types.

How do I get the latest year in SQL?

MySQL YEAR() Function The YEAR() function returns the year part for a given date (a number from 1000 to 9999).

What is MySQL Curdate?

CURDATE() Returns the current date as a value in ' YYYY-MM-DD ' or YYYYMMDD format, depending on whether the function is used in string or numeric context. mysql> SELECT CURDATE(); -> '2008-06-13' mysql> SELECT CURDATE() + 0; -> 20080613.


2 Answers

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

like image 116
Dan Grossman Avatar answered Oct 20 '22 03:10

Dan Grossman


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 date field.

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


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; 
like image 21
Mchl Avatar answered Oct 20 '22 05:10

Mchl