MYSQL的随机抽取实现方法。举个例子,要从tablename表中随机提取一条记录,大家一般的写法就是:SELECT * FROM tablename ORDER BY RAND() LIMIT 1
但是,后来我查了一下MYSQL的官方手册,里面针对RAND()的提示大概意思就是,在ORDER BY从句里面不能使用RAND()函数,因为这样会导致数据列被多次扫描。但是在MYSQL 3.23版本中,仍然可以通过ORDER BY RAND()来实现随机。
但是真正测试一下才发现这样效率非常低。一个100万余条的库,查询1条数据,居然要4秒以上。查看官方手册,也说rand()放在ORDER BY 子句中会被执行多次,自然效率及很低。
You cannot use a column with RAND() values in an ORDER BY clause, because ORDER BY would evaluate the column multiple times.
搜索Google,网上基本上都是查询max(id) * rand()来随机获取数据。
select * from instanceprice_attach where id <= (SELECT FLOOR(RAND() * (SELECT MAX(ID) FROM INSTANCEPRICE_ATTACH))) order by id limit 1
这样大概95ms。
原来写的是>=,一直是id最大的那条记录。
有人这样处理取得重复记录:
SELECT t1.*
FROM tablename AS t1 JOIN
(SELECT ROUND(RAND() * ((SELECT MAX(id) FROM tablename )-(SELECT MIN(id) FROM tablename ))+
(SELECT MIN(id) FROM tablename)) AS id) AS t2
WHERE t1.id >= t2.id
ORDER BY t1.id LIMIT 1;
SELECT * FROM tablename
WHERE id >= (SELECT floor( RAND() * ((SELECT MAX(id) FROM tablename )-
(SELECT MIN(id) FROM tablename )) + (SELECT MIN(id) FROM tablename )))
ORDER BY id LIMIT 1;
大概都是90多毫秒,网上说第一种写法会快一点,但是我测试貌似没什么区别。
(责任编辑:IT) |