Skip to content
Advertisement

Generate series of random size data in MySQL

I need to populate table with random size of data for each dependency record.

First table is table of products (named products):

And the second table is table that contains displays of that product (named product_displays). Each display is another row:

Like you can see date will always be the same value, but the number of rows that I need to insert should be random. And range for that number of returned rows I would like to specify in the query.

I except something like this:

For each product number of table_with_random_num_of_rows_between_x_and_y rows should be random.

Advertisement

Answer

If I followed you correctly, one simple solution is to join the products table with a table of numbers, using a random number as join condition, like:

This will produce a random number of records (between 1 and 5) for each product. You can expand the inline table to increase the maximum number of records per product. Alternatively, to manage a great (maximum) number of records, you can use a number table, or use row_number() and an already populated database table with a sufficient number of rows.

Demo on DB Fiddle (you can run the query several times to see the randomness in action):

id_product | pdate     
---------: | :---------
         1 | 2019-07-06
         1 | 2019-07-06
         1 | 2019-07-06
         1 | 2019-07-06
         1 | 2019-07-06
         2 | 2019-07-06
         2 | 2019-07-06
         2 | 2019-07-06
         3 | 2019-07-06
         3 | 2019-07-06
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement