Mysql之rand()随机取数

本文深入探讨了使用SQL语句随机读取表中一条记录的方法及性能优化策略,包括基于RAND()函数的两种实现方式,并通过EXPLAIN命令分析执行计划,以提升效率。

需求:

随机读取表的一条记录

数据准备:

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的部分进位。

  

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值