PHP MYSQL Query Algorithm Help
I'm a designing a website that orders results on its votes and ages.
I found the reddit algorithm and I think that is the best to use. However, I do not know how to implement this into php. I have searched google on how to do this but I cannot find any results. I don't know if it is just mean because I do not know exactly what I should be searching.
I know basic PHP however, is there a way of doing this in a simple way.
Is it possible to do it like this:
"SELECT * FROM table ORDER BY algorithm_here DES开发者_运维技巧C";
The reddit algorithm is as follows:
Log10(Z) + ((Y*Ts)/45000) = rank
A = time posted
B = 00:00:001 am 1/1/2010
U = Up votes
D = Down votes
Ts = A-B
X = U-D
Y =
1 if x>0
0 if x=0
-1 if x<0
z = max(abs(x),1)
Well if its me, i will write an UDF in MySQL called may be reddit_algo or something and use it like
SELECT
*,
reddit_algo() as rating
FROM
`table`
ORDER BY
`rating`
LIMIT 30;
If you want the stored function then here is it. i just wrote it fast and didnt get time to check it fully. I definitely hope this works. :)
DELIMITER &&
DROP FUNCTION IF EXISTS reddit_rank &&
CREATE FUNCTION reddit_rank(time_posted TIMESTAMP, up_votes INT, down_votes INT) RETURNS NUMERIC(10,6)
DETERMINISTIC
BEGIN
DECLARE start_time TIMESTAMP;
DECLARE Ts INT;
DECLARE vote_diff INT;
DECLARE y TINYINT;
DECLARE z1 INT;
DECLARE z INT;
DECLARE rank NUMERIC(10,6);
SET start_time = "2010-01-01 00:00:01";
SET Ts = TIMESTAMPDIFF(SECOND,start_time, time_posted);
SET vote_diff = up_votes - down_votes;
IF vote_diff > 0 THEN
SET y = 1;
ELSEIF vote_diff < 0 THEN
SET y = -1;
ELSE
SET y = 0;
END IF;
SET z1 = ABS(vote_diff);
IF z1 >= 1 THEN
SET z = z1;
ELSE
SET z = 1;
END IF;
SET rank = LOG10(z) + ( (y*Ts)/45000 );
RETURN(rank);
END &&
DELIMITER ;
SELECT
*,
reddit_rank(`time_added`, `up_votes`, `down_votes`) as rank
FROM
`table`
ORDER BY
rank;
Hope this helps. :) .. if u have any doughts on how to use a stored function and all try google searching.
Then again. I still want to say it again, it is not adivisable to use a stored function or any of such thing if you have a large database. So i strongly recommend to write a UDF. If you don't know how to do it; then for the time being adjust with this function and when the load increases and you start making lots of revenue get someone to write a UDF function for you. ;) ..
精彩评论