生成6个随机数而不重复MySQL

时间:2018-05-29 15:13:50

标签: mysql duplicates procedure generate

我需要一种智能方法来生成6个数字而不会在1到49之间重复,并将每个数字插入到列中。下面是我在phpmyadmin中创建的程序,它插入了重复的数字。

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 

2 个答案:

答案 0 :(得分:0)

你可以从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  

答案 1 :(得分:0)

选项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 ...