Solution to replace MYSQL “ORDER BY RAND()”

Some of you might be using the following directive to do Random Picking from your MYSQL database, which is mysql_query(“SELECT * FROM table ORDER BY RAND() LIMIT 10″);

However, It is not a good way if your website is in a high-flow-situation, Using such directive might causing a big loading in your hosting machine, here’s the alternative way to replace such directive, (special thanks to Nicky Soo for providing this method),

The code should be look like this:

mysql_query(” SELECT *
FROM news AS r1 JOIN
(SELECT (RAND() *
(SELECT MAX(newsid) FROM news)) AS newsid) As r2
WHERE `display` =1
AND r1.newsid >= r2.newsid
AND r1.counter >50
LIMIT 0 , 10  “)

Cheers!

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *