MySQL - getting from random column but specifying amounts
I would like to do this
SELECT *
FROM Thoughts
ORDER BY RAND()
LIMIT 1 WHERE ups > 5
...but it is returning an error. Do you know an alternative 开发者_运维技巧around that? I'm a bit new to MySQL, thanks.
The order of the clauses is important. Do
SELECT * FROM Thoughts WHERE ups > 5 ORDER BY RAND() LIMIT 1
Also, in the future, post the error you that you're getting. "An error" is amazingly unspecific.
order by rand() may cause performance issue, instead try to do in following way:
// what NOT to do:
$r = mysql_query("SELECT * FROM Thoughts WHERE ups > 5 ORDER BY RAND() LIMIT 1");
// much better:
$r = mysql_query("SELECT count(*) FROM Thoughts WHERE ups > 5 ");
$d = mysql_fetch_row($r);
$rand = mt_rand(0,$d[0] - 1);
$r = mysql_query("SELECT * FROM Thoughts WHERE ups > 5 LIMIT $rand, 1");
精彩评论