jeudi 23 novembre 2017

MySQL retrieving random tuples not working

The following code is supposed to retrieve a random idProduct from a table where the idProduct hasn't been used with the same idOrder. The problem is we are expecting a random number from 1 to 11, but we always get these numbers in a descending order.

delimiter //
CREATE DEFINER = 'root'@'localhost'
PROCEDURE populate()
BEGIN
  DECLARE i INT default 1;
  declare quantity int default 0;
  DECLARE j INT default 1;
  while i <= 1500 do
    set j = floor(RAND()*(5)+1);
    while j <= 10 do
        set quantity = floor(RAND()*(900)+100);
        select @product := idProduct from Product where idProduct
            not in (select idProduct from Parcel where idOrder = i) order by RAND() limit 1;
      insert into DB.Table(idProduct, idOrder, quantity) values (@product, i, quantity);
      set j = j + 1;
    end while;
    set i = i + 1;
  end while;
    END ; //
delimiter ;


We always get results like these:
idProduct   idOrder
11          1
10          1
9           1
8           1
7           1
6           1
11          2
10          2
9           2
8           2
7           2




Aucun commentaire:

Enregistrer un commentaire