mysql随机取出若干条记录的实用方法

1、常见的方法

1 select * from users where role_id=2 order by RAND() limit 2;

这种方法可以随机取得数据,但是如果表比较大,数据量很多的时候会很耗时

2、优化后的方式

select *  FROM  czhy_agent_number  where  id  in  (select  t.id  from  (select id from czhy_agent_number where user_id=100002 and type=1 ORDER BY RAND() limit 2)  as  t );

分析,首先根据条件筛选出要选的数据,然后随机排序取出要的条数的id ,(由于limit和in不能连着用,所有还需嵌套一层查出id供后面in使用

原文地址:https://www.cnblogs.com/myIvan/p/9753538.html