Mysql 随机获取n条数据,多种实现

  1. 简短使用,但不适用大型表,查询速度一般
    SELECT * FROM games ORDER BY RAND() LIMIT 10;
  2. 速度极快,但是数据是连续的(就是随机在表中某一行开始读取,后面的n行都是在这一行后面连续读取的)
    select * from games AS t1
    JOIN ( SELECT ROUND( RAND() * ( SELECT MAX( id ) FROM `games` )) AS id ) AS t2 
    where t1.id >= t2.id 
    order by t1.id asc 
    LIMIT 10;
  3. 速度极快,数据不连续读取,可以用
    select * from games 
    where id >= ( SELECT floor( RAND() * ( SELECT MAX( id ) FROM `games` ) ) ) 
    ORDER by id 
    LIMIT 10;

你可能感兴趣的:(mysql,数据库)