根据另一个表中的列值多次INSERT行

时间:2015-01-26 10:13:26

标签: mysql

主要是,我想根据表2列中的整数值多次在表1中插入一行。

我的情况

表2包含一栏' SKU'和' stock',我想插入' SKU'和表1中的时间戳。我希望此行重复表1中的' stock' -value次。

我目前有以下查询:

DECLARE @Count int = 1
WHILE @Count <= ....
BEGIN
    INSERT INTO table1 (table1.SKU, table1.timestamp_in) 
    SELECT table2.SKU, "some timestamp" FROM table2
    SET ...
END

我不确定这是否是正确的做法。我想为&#39; table2.stock&#39;运行这个循环。次。

我的问题是:这只是一个SQL查询是否可行,或者为此构建一些(在我的情况下)java代码应该是更好的做法?

1 个答案:

答案 0 :(得分:3)

您不需要程序或类似的东西。您只需要一个只包含数字的表格。我在这个例子中动态创建了这个表:

SELECT aa.a + 10*bb.b + 100*cc.c AS numbers FROM (
SELECT 0 a 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) aa 
, (SELECT 0 b 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) bb 
, (SELECT 0 c 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) cc;

这会创建数字0到999。

现在,您将table2与stock范围内的数字表联系起来。您的最终查询如下所示:

INSERT INTO table1 (table1.SKU, table1.timestamp_in) 
SELECT table2.SKU, "some timestamp" FROM table2
INNER JOIN (
    SELECT aa.a + 10*bb.b + 100*cc.c AS n FROM (
    SELECT 0 a 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) aa 
    , (SELECT 0 b 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) bb 
    , (SELECT 0 c 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) cc
) numbers ON numbers.n BETWEEN 0 AND table2.stock /*assuming you have no negative stock*/

请确保数字表包含的数字多于库存列中的最高值。