生成6个无重复的随机数

cqoc49vn  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(468)

这个问题在这里已经有了答案

如何在mysql存储过程中生成5个随机数(1个答案)
两年前关门了。
我需要一个聪明的方法,生成6个数字之间没有重复1和49,并插入每个数字列。下面是我在phpmyadmin中创建的procedere,它插入带有重复项的数字。

BEGIN

DECLARE liczba1 INT;
DECLARE liczba2 INT;
DECLARE liczba3 INT;
DECLARE liczba4 INT;
DECLARE liczba5 INT;
DECLARE liczba6 INT;
DECLARE check INT;
DECLARE count1 INT;
set count1 = 0;

while count1 < howMany DO
SELECT FLOOR(RAND()*(49-1)+1) into liczba1;
SELECT FLOOR(RAND()*(49-1)+1) into liczba2;
SELECT FLOOR(RAND()*(49-1)+1) into liczba3;
SELECT FLOOR(RAND()*(49-1)+1) into liczba4;
SELECT FLOOR(RAND()*(49-1)+1) into liczba5;
SELECT FLOOR(RAND()*(49-1)+1) into liczba6;
INSERT INTO kupony VALUES(NULL, 1, liczba1, liczba2, liczba3, liczba4, liczba5, liczba6, -1, '2018-01-01', -1);
set count1 = count1 + 1;
end while;

END
bt1cpqcv

bt1cpqcv1#

你能从9到9插入你的数字吗,比如liczba1在1到9之间,liczba2在10到18之间,liczba3在19到27之间。。。比如:

BEGIN

DECLARE liczba1 INT;
DECLARE liczba2 INT;
DECLARE liczba3 INT;
DECLARE liczba4 INT;
DECLARE liczba5 INT;
DECLARE liczba6 INT;
DECLARE check INT;
DECLARE count1 INT;
set count1 = 0;

while count1 < howMany DO
SELECT FLOOR(RAND()*(9-1)+1) into liczba1;
SELECT FLOOR(RAND()*(9-1)+9) into liczba2;
SELECT FLOOR(RAND()*(9-1)+18) into liczba3;
SELECT FLOOR(RAND()*(9-1)+27) into liczba4;
SELECT FLOOR(RAND()*(9-1)+36) into liczba5;
SELECT FLOOR(RAND()*(5-1)+45) into liczba6;
INSERT INTO kupony VALUES(NULL, 1, liczba1, liczba2, liczba3, liczba4, liczba5, liczba6, -1, '2018-01-01', -1);
set count1 = count1 + 1;
end while;

END
htzpubme

htzpubme2#

方案1:
您可以将随机数计算成一个循环,当所有数字都不同时退出循环:

while count1 < howMany DO
    /* loop until all are differents */
    myloop: while 
      SELECT FLOOR(RAND()*(49-1)+1) into liczba1;
      SELECT FLOOR(RAND()*(49-1)+1) into liczba2;
      SELECT FLOOR(RAND()*(49-1)+1) into liczba3;
      SELECT FLOOR(RAND()*(49-1)+1) into liczba4;
      SELECT FLOOR(RAND()*(49-1)+1) into liczba5;
      SELECT FLOOR(RAND()*(49-1)+1) into liczba6;
      select n = count( distinct n ) 
      from ( select liczba1 union select liczba2 union ... ) T
      if n = 9 then 
          LEAVE myloop;
      end if;
    end while myloop
    /* here all are differents */
    INSERT INTO kupony ...
    ...

免责声明:未测试,可能是一些打字错误。
方案2:
您可以使用视图计算出一些不同的随机数并将其插入:

/* https://stackoverflow.com/a/9751493/842935 */
CREATE OR REPLACE VIEW generator_16
AS 
   SELECT 0 n UNION ALL SELECT 1  UNION ALL SELECT 2  UNION ALL 
   SELECT 3   UNION ALL SELECT 4  UNION ALL SELECT 5  UNION ALL
   SELECT 6   UNION ALL SELECT 7  UNION ALL SELECT 8  UNION ALL
   SELECT 9   UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL
   SELECT 12  UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL 
   SELECT 15;

CREATE OR REPLACE VIEW get_6 
AS
  SELECT n FROM generator_16 ORDER BY rand() LIMIT 6;

DECLARE b1, b2, b3 INT;
DECLARE cur1 CURSOR FOR select * from get_6
OPEN cur1;
FETCH cur1 INTO b1;
FETCH cur1 INTO b2;
FETCH cur1 INTO b3;
CLOSE cur1;    
INSERT INTO kupony ...

相关问题