mysql order by rand() 优化方法

mysql order by rand() 优化方法
mysql> select * from user order by rand() limit 1;
+-------+------------+----------------------------------+----------+--------------+-----------+
| id    | phone      | password                         | salt     | country_code | ip        |
+-------+------------+----------------------------------+----------+--------------+-----------+
| 15160 | 6549721306 | e4f302120c006880a247b652ad0e42f2 | 40343586 | 86           | 127.0.0.1 |
+-------+------------+----------------------------------+----------+--------------+-----------+
1 row in set (0.25 sec)
mysql> explain select * from user order by rand() limit 1;
+----+-------------+-------+------+---------------+------+---------+------+--------+---------------------------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows   | Extra                           |
+----+-------------+-------+------+---------------+------+---------+------+--------+---------------------------------+
|  1 | SIMPLE      | user  | ALL  | NULL          | NULL | NULL    | NULL | 200303 | Using temporary; Using filesort |
+----+-------------+-------+------+---------------+------+---------+------+--------+---------------------------------+
1 row in set (0.00 sec)
根据分析结果,运行需要0.25秒,order by rand() 需要使用临时表(Using temporary),需要使用文件排序(Using filesort),效率低下。 改进方法

   
   
mysql> select * from user limit 23541,1;
+-------+------------+----------------------------------+----------+--------------+-----------+
| id    | phone      | password                         | salt     | country_code | ip        |
+-------+------------+----------------------------------+----------+--------------+-----------+
| 23542 | 3740507464 | c8bc1890de179538d8a49cc211859a46 | 93863419 | 86           | 127.0.0.1 |
+-------+------------+----------------------------------+----------+--------------+-----------+
1 row in set (0.01 sec)

mysql> explain select * from user limit 23541,1;
+----+-------------+-------+------+---------------+------+---------+------+--------+-------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows   | Extra |
+----+-------------+-------+------+---------------+------+---------+------+--------+-------+
|  1 | SIMPLE      | user  | ALL  | NULL          | NULL | NULL    | NULL | 200303 | NULL  |
+----+-------------+-------+------+---------------+------+---------+------+--------+-------+
1 row in set (0.00 sec)


查看原文:http://newmiracle.cn/?p=1743
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值