SQL查询将一行中的单行插入另一个表中的多行

时间:2014-01-24 00:00:36

标签: mysql sql sql-server sql-server-2008

我有桌子 TABLE_1:

PID DIV1 DES1 DIV2 DES2 DIV3 DES3  DIV4  DES4 DIV5  DES5
1    D1   DS1 D2  DS2    D3   DS3  null  null D5    null

输出

TABLE_2:

TID PID DIV DES
001  1   D1  DS1
002  1   D2  DS2
003  1   D3  DS3
004  1   D5  null

我需要将insert语句从table_1插入到table_2。如果表在DIV和DES上都有空值,那么我不应该插入这些字段。

谢谢

1 个答案:

答案 0 :(得分:2)

在SQL Server中,您可以使用

WITH a(PID, DIV, DES, NO) as (
    SELECT PID, DIV1, DES1, 1 FROM table_1 WHERE DIV1 IS NOT NULL OR DES1 IS NOT NULL
    UNION ALL
    SELECT PID, DIV2, DES2, 2 FROM table_1 WHERE DIV2 IS NOT NULL OR DES2 IS NOT NULL
    UNION ALL
    SELECT PID, DIV3, DES3, 3 FROM table_1 WHERE DIV3 IS NOT NULL OR DES3 IS NOT NULL
    UNION ALL
    SELECT PID, DIV4, DES4, 4 FROM table_1 WHERE DIV4 IS NOT NULL OR DES4 IS NOT NULL
)
INSERT INTO table_2(TID, PID, DIV, DES)
SELECT ROW_NUMBER() OVER(order by PID, NO), PID, DIV, DES FROM a

在MySQL中,您可以将其更改为

INSERT INTO table_2(TID, PID, DIV, DES)
SELECT @i := @i + 1, PID, DIV, DES
  FROM (
    SELECT PID, DIV1 as DIV, DES1 as DES, 1 as NO FROM table_1 WHERE DIV1 IS NOT NULL OR DES1 IS NOT NULL
    UNION ALL
    SELECT PID, DIV2, DES2, 2 FROM table_1 WHERE DIV2 IS NOT NULL OR DES2 IS NOT NULL
    UNION ALL
    SELECT PID, DIV3, DES3, 3 FROM table_1 WHERE DIV3 IS NOT NULL OR DES3 IS NOT NULL
    UNION ALL
    SELECT PID, DIV4, DES4, 4 FROM table_1 WHERE DIV4 IS NOT NULL OR DES4 IS NOT NULL
   ) AS a,
   (select @i := 0) AS temp
order by PID, NO