首页 > 数据库技术 > 详细

Mysql之rand()随机取数

时间:2015-06-30 02:08:04      阅读:250      评论:0      收藏:0      [点我收藏+]

需求:

随机读取表的一条记录

数据准备:

1.表结构

mysql> desc tb_random;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(200) | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+

数据量:百万

?

实现:

1.基于rand()

SELECT * FROM tb_random   ORDER BY rand() LIMIT 1; 

2.基于随机id取值,借助rand()和FLOOR()

SELECT * FROM tb_random WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM tb_random ) ORDER BY id LIMIT 1;  

性能可以通过explain来看执行计划:

explain SELECT * FROM tb_random   ORDER BY rand() LIMIT 1 \G;  

结果:

*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: tb_random
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 15995114
        Extra: Using temporary; Using filesort
1 row in set (0.00 sec)

结论:没有采用索引

?

第二种方案:

explain SELECT * FROM tb_random WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM tb_random ) ORDER BY id LIMIT 1 \G;  

结果:

*************************** 1. row ***************************
           id: 1
  select_type: PRIMARY
        table: tb_random
         type: index
possible_keys: NULL
          key: PRIMARY
      key_len: 4
          ref: NULL
         rows: 1
        Extra: Using where
*************************** 2. row ***************************
           id: 2
  select_type: UNCACHEABLE SUBQUERY
        table: tb_random
         type: index
possible_keys: NULL
          key: PRIMARY
      key_len: 4
          ref: NULL
         rows: 15995114
        Extra: Using index
2 rows in set (0.00 sec)

结论:using index

?

PS:

mysql函数 写道
floor:函数只返回整数部分,小数部分舍弃。
round:函数四舍五入,大于0.5的部分进位。

??

?

?

Mysql之rand()随机取数

原文:http://snv.iteye.com/blog/2222882

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!