tags:

views:

185

answers:

4

I have a table with a date stamp E.g (1241037505). There's also a column with the number of views.

The data stamp resembles when it was created.

So I want to select the top viewed threads from the past week.

How do I do this?

A: 
SELECT * FROM table WHERE Date_Created > (7 days ago value) ORDER BY Hits LIMIT 0,100

or you could use this (per WishCow's Answer)

SELECT * FROM table WHERE Date_Created > SUBDATE(NOW(), '7 day') ORDER BY Hits LIMIT 0,100
Chacha102
What is the value of 7 days ago?
Ben Shelock
@Ben Shelock, (now value) - (7 * 24 * 60 * 60).In php it would be time() - (7 * 24 * 60 * 60)
Nathan
You need to calculate that. Through PHP you could use time()-604800.
Chacha102
Erm... I think you mean greater than; not 'where date created is less than (i.e. before) 7 days ago'
jason
Yep, Edited. There you go.
Chacha102
+1  A: 
SELECT * FROM table WHERE createdon > SUBDATE(NOW(), '7 day') ORDER BY hits DESC;

See: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_subdate

WishCow
+1  A: 

The data you're currently tracking isn't going to allow you to select the top viewed in the last week. It will show you the top viewed over all time, or the most viewed items created in the last week. If something was created two weeks ago, but was viewed more than anything else during the last week you cannot determine that from the data you're tracking. One way I can see to do it would be to track the number of hits each content item gets each day of the week.

create table daily_hits {
    cid integer, -- content id points to the table you already have
    dotw smallint, -- 0-6 or similar
    hits integer
    PRIMARY KEY (cid, dotw)
}

Whenever you increase the hit count on the content item, you would also update the daily_hits table for the given content id and day of the week. You would need a function that converted the current date/time to a day of the week. MySql provides DAYOFWEEK for this purpose.

To get the most viewed in the last week, you could query like this:

SELECT cid, SUM(hits) FROM daily_hits GROUP BY cid ORDER BY SUM(hits) DESC

You will need some type of scheduled job that deletes the current day of the week at midnight so you aren't accumulating forever and essentially performing the same accumulation happening on the hits column of the current table.

David Smith
I think he wants to see the top viewed created in the last week. But I might be wrong.
Chacha102
I was a little confused about that too. Since he wants most viewed, I thought the created time wasn't relevant. I chose the opposite direction with the hope maybe it was more what he was looking for.
David Smith
+1  A: 

Try this:

SELECT * WHERE
DATEDIFF(NOW(),created_date) < 7
Elzo Valugi
His question indicated his time column is a unix timestamp. You will have to call `FROM_UNIXTIME()` on its value first, to convert it to a native MySQL datetime value.
jason