Home > Database > Mysql Tutorial > sql 随机函数newID()和RAND()详解 

sql 随机函数newID()和RAND()详解 

WBOY
Release: 2016-06-07 17:47:58
Original
1980 people have browsed it

sql 随机函数newid()和rand()详解  

   * from northwind..orders order by newid()

下者效率要高些

   select   top   10   *,newid()   as   random   from   ywle where   ywlename='001'   ordey   by   random

--随机排序

  select top 10 * from northwind..orders order by newid()

--从orders表中随机取出10条记录 

那就看下面的两种随机取整数的方法:

1、
a:select  floor(rand()*n)  ---生成的数是这样的:12.0
b:select cast( floor(rand()*n) as int)  ---生成的数是这样的:12

2、
a:select ceiling(rand() * n)  ---生成的数是这样的:12.0
b:select cast(ceiling(rand() * n) as int)  ---生成的数是这样的:12

    其中里面的n是一个你指定的整数,如100,可以看出,两种方法的a方法是带有.0这个的小数的,而b方法就是真正的整数了。
    大致一看,这两种方法没什么区别,真的没区别?其实是有一点的,那就是他们的生成随机数的范围:
方法1的数字范围:0至n-1之间,如cast( floor(rand()*100) as int)就会生成0至99之间任一整数
方法2的数字范围:1至n之间,如cast(ceiling(rand() * 100) as int)就会生成1至100之间任一整数

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template