views:

69

answers:

1

I only have two variables to work with here, age (unix timestamp) and hits. I'm wondering if there is a solution in MySQL to calculate and order by the popularity of something. The algorithm would have to acknowledge that new items would not necessarily have as many hits as older ones but are more popular.

Is this possible the way I'm imagining it?

+2  A: 

You need to come up with your own method of weighting hits and age when calculating popularity. You can select this function as popularity, and then order on this. The following simple example orders on the daily hit ratio of the page.

SELECT table.*, (table.hits / TIMESTAMPDIFF(DAY, NOW(), FROM_UNIXTIME(table.created))) AS popularity
FROM table
...
ORDER BY popularity DESC
Zed
This works really well, thanks. Now things that are getting lots of traffic in short periods of time are starting to compete with other content that is much older.
Sam152
Keep in mind that MySQL can't use an index to speed your ORDER BY clause. Afaik MySQL doesn't support function based indices and so your query will always end up in a full table scan.
VolkerK
Absolutely correct. Thanks for pointing this out. I guess a solution is to have the popularity as a field in the table, updated regularly by some background process.
Zed
Or calculate popularity on a basis that doesn't require continuous updating - such as assigning each record a number that is increasing for newer items and for higher popularity.
Nick Johnson