mysql order by rand() limit $num 优化
2022-03-28 / SQL / 2517 次围观 / 0 次吐槽 /优化写法前:
select * from ay_content where status=1 order by rand() limit 1
select id,typename,typeimg from dede_arctype where ishidden=0 and reid!=0 and typeimg!='' order by rand() limit $num
这种写法在数据量大的时候速度非常慢,优化写法后查询速度提升很大。
优化写法后:
SELECT * FROM `ay_content` AS t1 JOIN ( SELECT FLOOR( rand() * ( SELECT id FROM `ay_content` ORDER BY id DESC LIMIT 1 )) AS id ) AS t2 WHERE t1.id >= t2.id LIMIT 1
SELECT id,typename,typeimg FROM `dede_arctype` WHERE ishidden=0 and reid!=0 and typeimg!='' and id >= (SELECT floor( RAND() * ((SELECT MAX(id) FROM `dede_arctype`)-(SELECT MIN(id) FROM `dede_arctype`)) + (SELECT MIN(id) FROM `dede_arctype`))) ORDER BY id LIMIT $num
Powered By Cheug's Blog
Copyright Cheug Rights Reserved.