您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

mysql随机查询的优化

2024/5/14 11:37:54发布47次查看
mysql随机查询最常见的写法如下: 1 select * from tablename order by rand() limit 1 php手册上如此解释: about selecting random rows from a mysql table: select * from tablename order by rand() limit 1 works for small tables, but once the tables
mysql随机查询最常见的写法如下:
1 select * from tablename order by rand() limit 1
php手册上如此解释:
about selecting random rows from a mysql table:
select * from tablename order by rand() limit 1
works for small tables, but once the tables grow larger than 300,000 records or so this will be very slow because mysql will have to process all the entries from the table, order them randomly and then return the first row of the ordered result, and this sorting takes long time. instead you can do it like this (atleast if you have an auto_increment pk):
select min(id), max(id) from tablename;
fetch the result into $a
$id=rand($a[0],$a[1]);
select * from tablename where id>=’$id’ limit 1.
大意是说,如果你用 order by rand() 来随机读取记录的话,当数据表记录达到30万或者更多的时候,mysql将非常吃力.所以php手册里给了一种方法,结合php来实现:
首先 select min(id), max(id) from tablename; 取数据库里最大最小值;
然后 $id=rand($a[0],$a[1]); 产生一个随机数;
最后 select * from tablename where id>=’$id’ limit 1 将上面产生的随机数带入查询;
很显然上面是最有效率的。
如果需要多条记录的话,就循环查询,并记得去除重复记录。
其它的一些方法可以自行查阅一下google或者百度。

该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product