views:

36

answers:

3

Here is my code so far:

SELECT `date`, title, category, url
FROM cute_news
WHERE category = '4'
ORDER BY `date` DESC

I want make pages based on the year, like, 2010 , 2009, 2008 and so on. The database saves the date as UNIX_Timestamp. Not sure how to query a recordset with a Year parameter?

WHERE unix_timestamp(YEAR) = '2010' or something???

Thanks in advance. I'm baffled.

+3  A: 

You'll want something like WHERE YEAR(FROM_UNIXTIME(date_field)) = 2010.

konforce
Perfect :-) I knew I was missing something simple ha.
eberswine
@eberswine: Keep in mind that such a query will be slow if you will be having many rows in your table. The database would need to do a full table scan to filter down the rows you want... On the other hand, if you create an index on the `date` column (assuming one doesn't already exist), you can use the `UNIX_TIMESTAMP()` function as in the second example in my answer. The database would then be able to use the index to quickly find the rows that you want without doing a full table scan.
Daniel Vassallo
@Daniel, that's true if the date field is the best discriminator. Often it is, and of course, there's no harm in giving MySQL the option via your recommendation even if it doesn't need it.
konforce
A: 

Try:

WHERE YEAR(FROM_UNIXTIME(`date`)) = 2010;
kovshenin
+1  A: 

You can use the FROM_UNIXTIME() function, but be aware that this will not use an index on the date column, if one exists:

... WHERE YEAR(FROM_UNIXTIME(`date`)) = 2010

For your query to be sargable, you could use the the UNIX_TIMESTAMP() function instead:

... WHERE `date` >= UNIX_TIMESTAMP('2010-01-01 00:00:00') AND 
          `date` < UNIX_TIMESTAMP('2011-01-01 00:00:00')
Daniel Vassallo