搜索了mysql随机查询,都是没有带where条件的,直接硬套的话limit获取到的记录个数不确定就需要一个while循环知道获取到需要的记录数,加了while循环的效率当然是很低很低的。也试了从数据库直接拿全部满足where条件的记录,再在java里面随机拿若干个,这也肯定是不合理的,效率跟记录总数有关跟所需记录无关,效率也非常低。求高手指点解决方法
解决方案
15
SELECT * FROM table
WHERE id >= (
(SELECT MAX(id) FROM table WHERE xxx = “xxx”)-
(SELECT MIN(id) FROM table WHERE xxx= “xxx”)
) * RAND() + (SELECT MIN(id) FROM table WHERE xxx= “xxx”)
LIMIT n 满足where条件的随机数 取n条数据 试试题主
WHERE id >= (
(SELECT MAX(id) FROM table WHERE xxx = “xxx”)-
(SELECT MIN(id) FROM table WHERE xxx= “xxx”)
) * RAND() + (SELECT MIN(id) FROM table WHERE xxx= “xxx”)
LIMIT n 满足where条件的随机数 取n条数据 试试题主
10
先看 where 后符合条件的有多少条,然后再讨论。
15
测试表,仅主键
CREATE TABLE `test` ( `sss` varchar(20) NOT NULL, PRIMARY KEY (`sss`) ) ENGINE=InnoDB DEFAULT CHARSET=gbk;
生成100W数据
CREATE PROCEDURE `aa`() BEGIN DECLARE i int; DECLARE c int; set i = 0; set autocommit = 0; while i < 1000 do set c = 0; while c < 1000 do insert into test VALUES( LPAD(i*1000+c,10,"0")); set c=c+1; end while; commit; set i=i+1; end while; set autocommit = 1; END
查询
select * from test WHERE sss > "0000100023" and sss < "0000200023" ORDER BY rand() LIMIT 100
耗时0.12S, 服务器是阿里云RDS最低配置。
ORDER BY rand() LIMIT N会慢吗?