mysql select rand,Mysql:RAND函数与limit结合的妙用

RAND()函数在mysql中是取随机数。范围是[0,1]。

mysql> select rand();

+——————+

| rand()           |

+——————+

| 0.47331121980521 |

+——————+

1 row in set (0.00 sec)

mysql> select rand();

+——————+

| rand()           |

+——————+

| 0.37024365586251 |

+——————+

1 row in set (0.00 sec)

其实它还有两个妙用:

1.取随机正数:

若要在i ≤ R ≤ j 这个范围得到一个随机整数R ,需要用到表达式 FLOOR(i + RAND() * (j – i + 1))。例如, 若要在7 到 12 的范围(包括7和12)内得到一个随机整数, 可使用以下语句:

SELECT FLOOR(7 + (RAND() * 6));

2.与limit配合,取随机数据。格式是:select * from an_idb3 order by rand() limit 5;

原表数据:

mysql> select * from an_idb3;

+——+——+————–+

| id   | name | email        |

+——+——+————–+

|    1 | an   | an@mail.com  |

|    2 | an2  | an2@mail.com |

|    1 | an   | an@mail.com  |

|    2 | an   | an@mail.com  |

|    3 | an   | an@mail.com  |

|    5 | an5  | an@mail.com  |

|    6 | an6  | an@mail.com  |

| NULL | an7  | an7@mail.com |

| NULL | NULL | NULL         |

+——+——+————–+

9 rows in set (0.00 sec)

取两组随机数(每组5条):

mysql> select * from an_idb3 order by rand() limit 5;

+——+——+————-+

| id   | name | email       |

+——+——+————-+

|    5 | an5  | an@mail.com |

| NULL | NULL | NULL        |

|    6 | an6  | an@mail.com |

|    3 | an   | an@mail.com |

|    1 | an   | an@mail.com |

+——+——+————-+

5 rows in set (0.00 sec)

mysql> select * from an_idb3 order by rand() limit 5;

+——+——+————-+

| id   | name | email       |

+——+——+————-+

|    1 | an   | an@mail.com |

| NULL | NULL | NULL        |

|    1 | an   | an@mail.com |

|    5 | an5  | an@mail.com |

|    6 | an6  | an@mail.com |

+——+——+————-+

5 rows in set (0.00 sec)

本文结束,谢谢观赏

赞过:

赞 正在加载……

相关

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值