如何基于现有表生成sql数据?

kxeu7u2r  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(238)

最近,为了做一些基本的测试,我不得不创建大约300000行的数据库。我不得不“手动”创建表customer、product和supplier—它们包含大约3000行。
现在我只能根据这3个表中的数据正确填写order和orderitem表。所以我的问题是,如何仅使用sql查询和约束生成超过200000行order和orderitem?我知道如何手动添加(一行一行),但那需要几个星期。最糟糕的是,我被困在这几天,不能前进没有它。
我真的很抱歉问这个愚蠢的问题,但我真的很想得到任何帮助,提前谢谢你!
这是我数据库的e-r图:

v9tzhpje

v9tzhpje1#

假设customer&products表包含项。
你可以试试这样的方法:

-- Generage 1 year of dates
DECLARE @StartDate  date = '2020-01-01';
DECLARE @CutoffDate date = DATEADD(DAY, -1, DATEADD(YEAR, 1, @StartDate));

;WITH seq(n) AS 
(
    SELECT 0 UNION ALL SELECT n + 1 FROM seq
    WHERE n < DATEDIFF(DAY, @StartDate, @CutoffDate)
)
SELECT DATEADD(Day,n, GetDate()) Date 
INTO #Dates
FROM seq
ORDER BY n 
OPTION (MAXRECURSION 0);

-- Generates an Order for each customer for each date
INSERT INTO [Order](CustomerId, OrderDate, OrderNumber)
SELECT c.Id
    , d.Date
    , ROW_NUMBER() OVER (ORDER BY NewId())
FROM Customer c
-- Using join to filter out data, random customer on random date.
INNER JOIN #Dates d on abs(checksum(c.Id) % 2) = abs(checksum(d.Date) % 2)

-- Generate order items, for each order add 3 products with random price / quantity
INSERT INTO OrderItem(OrderId, ProductId, UnitPrice, Quantity)
SELECT x.OrderId, x.ProductId
—- , abs(checksum(NewId()) % 100) + 1 -- Random price between 1 and 100
, x.UnitPrice
,  abs(checksum(NewId()) % 10) + 1 -- Random quantity between 1 and 10
FROM (
    SELECT o.Id OrderId, p.Id ProductId,p.UnitPrice ROW_NUMBER() oVER (PARTITION BY o.Id ORDER BY NewId()) n
    FROM [Order] o, Product P
) x
WHERE x.N <= 3 -- Max 3 products per order

您可以多次运行底部查询,以便向订单中添加更多订单项(添加不同价格的重复产品的可能性)

nhhxz33t

nhhxz33t2#

您可以通过使用row\u number()随机生成随机数据,然后基于row\u number()进行连接。我们使用rand()函数生成随机量

;WITH CTE_RandomProduct as
(
SELECT *, ROW_NUMBER() OVER(ORDER BY NEWID()) as rnk
from Product
),
CTE_RandomOrder as
(
SELECT *, ROW_NUMBER() OVER(ORDER BY NEWID()) as rnk
from Order
)
INSERT INTO [OrderItem] ([OrderId],[ProductId],[UnitPrice],[Quantity])
SELECT o.orderId, p.productid,p.unitprice,cast((RAND(o.orderId)  * 100 ) as int) as quantity
from CTE_RandomProduct as p
INNER JOIN CTE_RandomOrder as o
on p.rnk = o.rnk
WHERE o.rnk < 10000 -- to restrict the number of rows

相关问题