1

我需要一种聪明的方法来生成 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 
4

2 回答 2

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 ...
于 2018-05-29T15:44:59.390 回答
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  
于 2018-05-29T15:25:28.303 回答