Take the 2-minute tour ×

With PHP and MySQL I am trying to display items with most votes over a certain period of time (24 hour, 1 week, 1 year, etc). When someone votes on an item, a table records the user, item id, vote, and time, like so:


username |  itemid | vote | time
   asdf  |    127  |   1  |  1306726126
   asdf  |    124  |  -1  |  1306726123
    bob  |    127  |   1  |  1306726129
    bob  |    124  |   1  |  1306726123

Now, I have another table with item details.


itemid  | name  | category | date | etc

What I WANT to do is call a table to display all the data from table 2 for only items with votes in the last 24hours and sort it by the votes. This means I need to SUM votes with TIME < 24 hours, then RIGHT JOIN (?) to my other database? I don't know, I am having difficulty figuring out how I should go about doing this. Any suggestiongs?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

Something like this should work.

SELECT SUM(Table1.vote) as votes, Table2.* FROM Table2            
    LEFT JOIN Table1 ON Table1.itemid=Table2.itemid                
    WHERE Table1.`time`>=DATE_SUB(Table1.`time`, INTERVAL 24 HOUR) 
GROUP BY Table1.itemid                                             
ORDER BY Table1.votes DESC  
share|improve this answer
Pretty sure this is it! Thank you! –  sanders4069 May 31 '11 at 17:39
add comment

Your Answer


