天天看點

mysql擷取随機範圍的正整數

使用rand()函數,傳回0-1的數。

rand()*N: 得到(0,N)浮點數字

floor(rand()*N+1): [1,N]的整數。

參見:尚矽谷資料庫課程,個人覺得課程很不錯的,還是免費。

例如:建立随機字元串(長度1-26)---------------僞随機

create procedure test_randstr_insert(IN insertCount int)
begin
	declare i int default 1;
	declare str varchar(26) default 'abcdefghijklmnopqrstuvwxyz';
	declare startIndex int default 1; # 代表起始索引
	declare len int default 1; # 代表長度
	while i<=insertCount do
		set startIndex = floor(rand()*26+1); # 産生一個随機整數1-26.
		set len = floor(rand()*(25-startIndex)+1) # 截取長度1~26-startIndex
		insert into stringcontent(content) values(substr(str,startIndex,len));
		set i= i+ 1;
	end while;
end $
           
莊周曉夢迷蝴蝶,望帝春心托杜鵑。 ——李商隐