MySQL中rand 產生隨機數代碼

來源:互聯網
上載者:User

要隨機產生字串代碼如下:

在mysql教程中定義一個隨機串的方法,然後再sql語句中調用此方法。

隨機串函數定義方法:
select round(round(rand(),4)*10000);
不用函數直接這樣就好了。

非得寫函數的話,就
delimiter $$

create
    function get_rand()
    returns int deterministic
    begin
 declare return_no int;
 select round(round(rand(),4)*10000) into return_no;
 return return_no;
    end$$

delimiter ;

使用隨機串函數方法樣本:
update demotable set demoname=rand_string(32) where id>23
直接執行即可。


我在最開始測試的時候,就是因為沒有加上min(id)的判斷,結果有一半的時間總是查詢到表中的前面幾行。
完整查詢語句是:
select * from `table`
where id >= (select floor( rand() * ((select max(id) from `table`)-(select min(id) from `table`)) + (select min(id) from `table`)))
order by id limit 1;
select *
from `table` as t1 join (select round(rand() * ((select max(id) from `table`)-(select min(id) from `table`))+(select min(id) from `table`)) as id) as t2
where t1.id >= t2.id
order by t1.id limit 1;
最後在php教程中對這兩個語句進行分別查詢10次,
前者花費時間 0.147433 秒
後者花費時間 0.015130 秒

以上就是mysql rand函數實現隨機數的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.