为什么rand()中的代码在mysql中不起作用?

时间:2015-07-03 02:02:52

标签: mysql sql

我的用户ID是guid,它不是int。首先,我用户ORDER BY RAND()并且它有效。但有人说它效率不高。所以我尝试将其改为其他方式。但它不能work.How如何解决?

-- work fine but not efficient 
select userid from user order by rand() LIMIT 1

-- do not work,always return the same row
 SELECT * FROM user WHERE userid >= ((SELECT MAX(userid) FROM user)
-(SELECT MIN(userid) FROM user)) * RAND() 
+ (SELECT MIN(userid) FROM _user) LIMIT 1

-- do not work,always return the same row
SELECT userid FROM user AS t1 JOIN (SELECT  RAND()
* (SELECT MAX(userid) FROM user) AS id) AS t2 
WHERE t1.userid >= t2.id
ORDER BY t1.userid ASC LIMIT 1;

1 个答案:

答案 0 :(得分:1)

您将guid视为整数。那是行不通的。问题不是rand(),而是对类型的错误处理。

可以提高查询效率的一种方法是执行以下操作:

select userid
from user
where rand() < 0.01
order by rand()
limit 1;

这大约需要1%的表,并将其用于排序。你可以将其形式化为:

select userid
from user cross join (select count(*) as cnt from user) params
where rand() < 100 / cnt
order by rand()
limit 1;

这将从表格中选择约100行并对其进行排序。排序100行并不是特别密集,因此在性能方面应该是合理的。并且,预期值为100行时,查询应该基本上永远不会失败至少获得一行。