How to create an array of years ordered by year using SQL & PHP ?

Hello,

I'm using the following php/sql query to calculate the number of years between my earliest and most recent database records:
$query_years = mysql_query("SELECT YEAR(MAX(date)) - YEAR(MIN(date)) FROM locations");

This returns a single value and what i require instead is an array of all the YEARS in year order so that any year where there isn't a specific record for that year is omitted...
e.g. if my database had 2 records dated 1983 and 2008 - then it should just return these 2 years in chronological order, rather than all 25 years between the two dates.


 - please can you show me how this is done?


Many thanks
DaniishAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Paul_Harris_FusionCommented:
I'm not familiar with MySQL but if I assume that the YEAR function extracts the year part of the date then the following should work (based on Oracle and SQLServer sql)

Select distinct YEAR(date) from locations
order by date

The distinct qualifier removes duplicates from the result set.

An alternative is
Select y from
(Select YEAR(date) as yfrom locations order by date) inner
group by y

In this example the inner query potentially returns returns duplicate years and these are removed by the outer group by clause

Hope this helps
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
nplibCommented:

$query_years = mysql_query("SELECT YEAR(MAX(date)) - YEAR(MIN(date)) FROM locations WHERE `date` BETWEEN YEAR(MAX(date)) AND YEAR(MIN(date)) ORDER BY `date`;");

Open in new window

0
cositollcCommented:
I'm not sure but try one of this:

$query_years = mysql_query("SELECT YEAR(MIN(date)),YEAR(MAX(date)) FROM locations ");

OR

$query_years = mysql_query("SELECT DISTINCT YEAR(date) FROM locations ");
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.