将数据从旧模式迁移到新模式

时间:2014-11-09 20:46:06

标签: mysql database migration database-migration

我有两个不同架构的表。我想将数据从旧模式中的表移动到新模式中的表。

SET foreign_key_checks = 0;

INSERT into newdb.Addresses (addressID, contactID, primaryFlag, type, address1, address2, poBox, city, state, zip, country, email)
SELECT address_id, contact_id, is_primary_address, 

    (SELECT address_type
    FROM test.address_types, test.contact_addresses
    WHERE test.contact_addresses.address_type_id = test.address_types.address_type_id),

    address_line_1, address_line_2, address_line_2, address_city, address_state, address_zip,

    (SELECT country
    FROM test.countries, test.contact_addresses
    WHERE test.contact_addresses.address_country_id = test.countries.country_id),

    address_email

FROM test.contact_addresses;

很抱歉,如果它是蹩脚的打字。基本上,当我运行查询时,它表示子查询返回多行。如何重构查询,以便子查询中返回的内容是引擎当前正在迭代的行(因此,只返回一行)?

2 个答案:

答案 0 :(得分:1)

您查询的选择部分缺少列,因为插入中的列与select中的列不匹配。此外,您不需要再次将所查询的子内部连接到外部表。

尝试将上面的查询更改为以下

这比上面的查询表现得更快,它会为您提供所需的信息。

INSERT INTO newdb.Addresses (.......)
SELECT a.address_id, a.contact_id, a.is_primary_address, t.address_type, c.country, a.address_email
FROM test.contact_addresses AS a
INNER JOIN test.address_types AS t ON t.address_type_id = a.address_type_id
INNER JOIN test.countries AS c ON c.country_id = a.country_id;

答案 1 :(得分:1)

您不需要子查询中的test.contact_addresses:

SELECT address_id, contact_id, is_primary_address, 

     (SELECT address_type
      FROM test.address_types AS at
      WHERE at.address_type_id = ca.address_type_id),

address_line_1, ....

FROM test.contact_addresses AS ca;

这样,SQL就会选择与外部查询中的adress_type_id相等的那个。