如何从其他表中获取记录的ID?

时间:2016-10-20 21:07:29

标签: mysql foreign-keys

我在MySQL中有一个数据库,我想迁移它,稍微改变一下表的结构。

我是MySQL的新手,请耐心等待。

我有以下表格:

地址

  • ADDRESS_ID
  • 地址(例如:55th Street)
  • ZIP_CODE
  • 城市
  • 国家

CustomersOld

  • CUSTOMER_ID
  • 名称
  • billing_address
  • billing_zip_code
  • billing_city
  • billing_country

我想将客户数据迁移到具有以下结构的新表中

CustomersNew

  • CUSTOMER_ID
  • billing_address_id(地址表的外键)

所以,我想从表 CustomersOld 中取出4个帐单地址字段并执行此操作:

  1. 检查地址表是否包含与帐单邮寄地址字段匹配的记录。

    1.1。如果是,则仅返回AddressID。

    1.2。如果不是,则创建该记录,并返回AddressID。

  2. 将AddressID插入CustomersNew表的address_id字段中。
  3. 通常,我使用这个简单的脚本来迁移表:

    INSERT INTO CustomersNew
    SELECT * FROM CustomersOld
    

    我想我必须执行一些嵌套的SELECT和JOIN:

    INSERT INTO CustomersNew
        (customer_id, billing_address_id)
    SELECT
        customer_id, 
        -- SELECT/JOIN ... (something like that, in order to get the address_id)
    FROM CustomersOld
    

    您可以帮助我为每个客户获取相应的billing_address_id吗?

    由于

2 个答案:

答案 0 :(得分:1)

这需要分两步完成。首先创建所有Addresses条记录:

INSERT INTO Addresses (address, zip_code, city, country)
SELECT DISTINCT billing_address, billing_zip_code, billing_city, billing_country
FROM CustomersOld;

然后通过将此表与CustomersNew

连接,创建所有CustomersOld条记录
INSERT INTO CustomersNew (customer_id, billing_address_id)
SELECT c.customer_id, a.address_id
FROM CustomersOld AS c
JOIN Addresses AS a ON c.billing_address = a.address AND c.billing_zip_code = a.zip_code AND c.billing_city = a.city AND c.billing_country = a.country

答案 1 :(得分:0)

我建议你这样

Firts将地址与最后一个CustomerOld地址对齐

insert into Addresses (address, zip_code, city, country )
select billing_address, billing_zip_code, billing_city, billing_country
from CustomerOld
where (billing_address, billing_zip_code, billing_city, billing_country ) not in 
            ( select address, zip_code, city, country
              from Addresses
              )

然后使用创建选择

创建和填充CustomersNew
create table CustomersNew
select a.customer_id, b.address_id
from CustomersOld as a 
inner join Addresses as b  on a.billing_address = b.address
    and a.billing_zip_code = b.zip_code
      and  a.billing_city = b.city
        and a. billing_country = b.country