最近做项目,需要做一个从mysql数据库中随机取几条数据出来. 总所周知,order by rand 会死人的..因为本人对大数据量方面的只是了解的很少,无解,去找百度老师..搜索结果千篇一律.特发到这里来,供大家学习. 在mysql中带了随机取数据的函数,在mysql中我们会有rand()函数,很多朋友都会直接使用,如果几百条数据肯定没事,如果几万或百万时你会发现,直接使用是错误的.下面我来介绍随机取数据一些优化方法. SELECT * FROM table_name ORDER BY ran
-- 随机获取 10 条数据 SQL Server:SELECT TOP 10 * FROM T_USER ORDER BY NEWID() ORACLE:SELECT * FROM (SELECT * FROM T_USER ORDER BY DBMS_RANDOM.RANDOM()) WHERE RONUM <= 10 MySQL:SELECT * FROM T_USER ORDER BY RAND() LIMIT 10 Access:SELECT TOP 10 * FROM T_USE
由于需要大概研究了一下MYSQL的随机抽取实现方法. 目前采用的方法: SELECT * FROM tablename ORDER BY RAND() LIMIT 实现原理: 通过ORDER BY RAND()来打乱数据的排序,LIMIT 来限制获取数据的条数. 缺点: 效率低.在进行大数据量检索时,会增加检索时间.一个15万余条的库,查询5条数据,居然要8秒以上. 官方手册说明,rand()放在ORDER BY 子句中会被执行多次,自然效率很低.
SQL Server: SELECT TOP 10 * FROM T_USER ORDER BY NEWID() ORACLE: SELECT * FROM (SELECT * FROM T_USER ORDER BY DBMS_RANDOM.RANDOM()) WHERE RONUM <= 10 MySQL: SELECT * FROM T_USER ORDER BY RAND() LIMIT 10
insert into result (user_id, activity_id, number) select user_id, activity_id from `activity_record` order by rand() LIMIT 20; select * into 表A form 表B where条件;
SELECT * FROM `table` AS t1 JOIN ( SELECT ROUND( RAND() * ( (SELECT MAX(id) FROM `table`) - (SELECT MIN(id) FROM `table`) ) + (SELECT MIN(id) FROM `table`) ) AS id ) AS t2 WHERE t1.id >= t2.id ORDER BY t1.id LIMIT 1;
方法一:新增models的Manager方法 下面就直接发代码了 class RandomManager(models.Manager): def get_queryset(self): return super(RandomManager, self).get_queryset().order_by('?') 使用的时候 class TrainWord(models.Model): ''' User train word ''' word = models.CharField(max_leng
本文详细解说了MySQL Order By Rand()效率优化的方案,并给出了优化的思路过程,是篇不可多得的MySQL Order By Rand()效率美文. 最近由于需要大概研究了一下MYSQL的随机抽取实现方法.举个例子,要从tablename表中随机提取一条记录,大家一般的写法就是:SELECT * FROM tablename ORDER BY RAND() LIMIT 1. 但是,后来我查了一下MYSQL的官方手册,里面针对RAND()的提示大概意思就是,在ORDER BY从句里面
一直以为mysql随机查询几条数据,就用 SELECT * FROM `table` ORDER BYRAND() LIMIT 5 就可以了. 但是真正测试一下才发现这样效率非常低.一个15万余条的库,查询5条数据,居然要8秒以上 查看官方手册,也说rand()放在ORDER BY 子句中会被执行多次,自然效率及很低. You cannot use a column with RAND() values in an ORDER BY clause, because ORDER BY would
今天做项目遇到这个问题,本来想用mysql自带的随机函数来实现,但是想到这样做功能是实现了,但是效率真的好差!一下子想不到好的方法,就去网上找了一下,记录下来,好好研究学习一下. ID连续的情况下(注意不能带where,否则结果不好): SELECT * FROM `talbe` AS t1 JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM `table`)) AS id) AS t2 WHERE t1.id >= t2.id ; ID不连续的情况