高洛峰2017-04-17 13:42:55
SELECT *
FROM 表名 AS t1
JOIN (
SELECT ROUND( RAND( ) * (SELECT MAX( id )FROM 表名 ) ) AS id
) AS t2
WHERE t1.id >= t2.id
ORDER BY t1.id ASC
LIMIT 50
阿神2017-04-17 13:42:55
This thing needs to be looked at separately.
If your table records do not have tens of thousands levels. Then order by rand()
is also acceptable.
But when the table records are large, order by rand()
the efficiency is extremely low.
So it is recommended to explain the business scenarios as much as possible on the basis of asking questions~~~.
PHP中文网2017-04-17 13:42:55
rand(), I vaguely remember that it was repeatedly emphasized in "High Performance MySQL" to avoid using it.
Based on the actual situation, if the data volume is not large, tens of thousands or hundreds of thousands, it can be used;
No matter how large it is, it is better to use a program to implement it, and then query it.
黄舟2017-04-17 13:42:55
rand() is fine, but please remember not to use SQL statements containing any calculations in online projects.