简体   繁体   English

MySQL生成一系列随机大小的数据

[英]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):第一张表是产品表(命名产品):

id || name
=== + =====
1  || name1
2  || name2
3  || name3

And the second table is table that contains displays of that product (named product_displays).第二个表是包含该产品显示的表(名为 product_displays)。 Each display is another row:每个显示是另一行:

id_product || date
=========== + ====
1          || d1
1          || d1
1          || d1
1          || d1
2          || d1
2          || d1
3          || d1
3          || d1
3          || d1

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:我除了这样的事情:

INSERT INTO product_displays (id_product, date)
SELECT
p.id,
'2019-07-06'
FROM products p
JOIN table_with_random_num_of_rows_between_x_and_y t

For each product number of table_with_random_num_of_rows_between_x_and_y rows should be random.对于每个产品, table_with_random_num_of_rows_between_x_and_y行的数量应该是随机的。

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:如果我没有跟着你,一个简单的办法就是joinproducts表数表,使用随机数作为加入条件,如:

insert into product_displays (id_product, pdate)
select p.id, '2019-07-06'
from products p
inner join (
    select 1 n union all select 2 union all select 3 union all select 4 union all select 5
) t on t.n <= floor(1 + rand() * 5)

This will produce a random number of records (between 1 and 5) for each product.这将为每个产品生成随机数量的记录(1 到 5 之间)。 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.或者,要管理大量(最大)记录,您可以使用数字表,或使用row_number()和已填充的具有足够行数的数据库表。

Demo on DB Fiddle (you can run the query several times to see the randomness in action): DB Fiddle 上的演示(您可以多次运行查询以查看操作中的随机性):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM