创建嵌套查询以将外部查询的结果输入到sql中的内部查询中

时间:2018-02-01 22:30:30

标签: sql rdms

我需要将值从一个表迁移到另一个表。但是,表和列的结构是不同的。

Table1 has one to one relationship with table2

Table1 (Saiyan). (latest table)
Id (PK), name.
1        Vegeta

Table2 (SaiyanPower) (latest table)
Identifier(PK), ID(FK),value1,     value2,       value3
1               1      SuperSaiyan SuperSaiyan2 SuperSaiyanBlue

Old Tables:
Table1 has one to many relationship

Table1 (old table) (SaiyanDistribution)
ID(PK), name.
1       Vegeta

Table2 (Old table) SaiyanDistributionValues
Identifier (PK), ID (FK), Value
1                1        SuperSaiyan
2                1        SuperSaiyan2
3                1        SuperSaiyanBlue

我需要将值从一个表迁移到另一个表。我不知道如何保存旧table1(SaiyanDistribution)的行,获取id以获取旧table2(SaiyanDistributionValue)的行,然后将其添加到新table1(Saiyan),new table2(SaiyanPower)。

2 个答案:

答案 0 :(得分:0)

忽略为什么这可能不是一个好主意,并假设在旧表中,对于Table1中每行的每个实例,Table2中最多有三行,每行Identifier等于1 ,2或3,您可以使用标量子查询执行此操作:

INSERT INTO NewTable2 (Identifier, ID, value1, value2, value3)
SELECT 1, ID,
    (SELECT Value FROM NewTable2 AS T1 WHERE T1.ID=NT2.ID AND Identifier=1),
    (SELECT Value FROM NewTable2 AS T2 WHERE T2.ID=NT2.ID AND Identifier=2),
    (SELECT Value FROM NewTable2 AS T3 WHERE T3.ID=NT2.ID AND Identifier=3)
FROM OldTable2 AS NT2
GROUP BY ID;

还有其他方法可以解决这个问题,例如在SELECT的FROM中将NewTable2连接到自身。但这显示了正在发生的事情并且应该以相同的方式执行。

答案 1 :(得分:0)

你的新基地不是一个好主意,即使你总是有3个价值。

无论如何,这是查询:

SQL Fiddle

MySQL 5.6架构设置

查询1

SELECT SD.ID, t1.Value, t2.Value, t3.Value
FROM SaiyanDistribution SD
INNER JOIN (
        SELECT `ID`, `Value`
        FROM SaiyanDistributionValues
        WHERE `Identifier` IN (
            SELECT MIN(`Identifier`)
            FROM SaiyanDistributionValues
            GROUP BY  ID
        )
    ) t1
    ON t1.ID = SD.ID
INNER JOIN (
        SELECT `ID`, `Value`
        FROM SaiyanDistributionValues
        WHERE `Identifier` NOT IN (
            SELECT MIN(`Identifier`)
            FROM SaiyanDistributionValues
            GROUP BY  ID
            UNION
            SELECT MAX(`Identifier`)
            FROM SaiyanDistributionValues
            GROUP BY  ID
        )
    ) t2
    ON t2.ID = SD.ID
INNER JOIN (
        SELECT `ID`, `Value`
        FROM SaiyanDistributionValues
        WHERE `Identifier` IN (
            SELECT MAX(`Identifier`)
            FROM SaiyanDistributionValues
            GROUP BY  ID
        )
    ) t3
    ON t3.ID = SD.ID

<强> Results

| ID |       Value |           Value |           Value |
|----|-------------|-----------------|-----------------|
|  1 | SuperSaiyan |    SuperSaiyan2 | SuperSaiyanBlue |
|  2 | SuperSaiyan | SuperSaiyanBlue |  SuperSaiyanRed |