如何生成 5 个随机数在 MySQL 存储过程中?
若要生成随机数,请在 MySQL 中使用 ORDER BY RAND() 函数。我们首先创建一个表 −
mysql> create table DemoTable (Value int); Query OK, 0 rows affected (0.76 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values(89); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(98); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.34 sec) mysql> insert into DemoTable values(78); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(75); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(76); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(74); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(99); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(101); Query OK, 1 row affected (0.15 sec)
使用 select 语句从表中显示所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+-------+ | Value | +-------+ | 89 | | 98 | | 10 | | 78 | | 75 | | 76 | | 74 | | 99 | | 101 | +-------+ 9 rows in set (0.00 sec)
以下是 MySQL 存储过程中生成 5 个随机数的查询 −
mysql> DELIMITER // mysql> CREATE PROCEDURE generate_Random5Numbers() BEGIN SELECT GROUP_CONCAT(Value SEPARATOR '/') FROM ( SELECT Value FROM ( SELECT Value FROM DemoTable WHERE Value BETWEEN 10 AND 100 ORDER BY RAND() LIMIT 5) Ascending_Order ORDER BY Value) 5Values; END // Query OK, 0 rows affected (0.31 sec) mysql> DELIMITER ;
使用 call 命令调用存储过程。
mysql> call generate_Random5Numbers();
这将产生以下输出 −
+-----------------------------------+ | GROUP_CONCAT(Value SEPARATOR '/') | +-----------------------------------+ | 89/74/78/99/10 | +-----------------------------------+ 1 row in set (0.00 sec) Query OK, 0 rows affected (0.02 sec)
广告