我在MySQL中有一个数据库,我想迁移它,稍微改变一下表的结构。
我是MySQL的新手,请耐心等待。
我有以下表格:
地址
CustomersOld
我想将客户数据迁移到具有以下结构的新表中
CustomersNew
所以,我想从表 CustomersOld 中取出4个帐单地址字段并执行此操作:
检查地址表是否包含与帐单邮寄地址字段匹配的记录。
1.1。如果是,则仅返回AddressID。
1.2。如果不是,则创建该记录,并返回AddressID。
通常,我使用这个简单的脚本来迁移表:
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
吗?
由于
答案 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
)
然后使用创建选择
创建和填充CustomersNewcreate 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