2016-10-20 20 views
1

私はMySQLにデータベースを持っており、テーブルの構造を少し変えて、それを移行したいと思います。他のテーブルからレコードのIDを取得する方法は?

私はMySQLの初心者ですので、私に同行してください。

私は以下の表を持っている:

アドレス

  • ADDRESS_ID
  • アドレス(例:第55回ストリート)
  • 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フィールドに挿入します。

    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 
    

    あなたが私を助けてもらえ:

    INSERT INTO CustomersNew 
    SELECT * FROM CustomersOld 
    

    、私はいくつかのネストされたSELECT文を実行しなければならず、JOINのだろうとします

通常、私はテーブルを移行するには、この簡単なスクリプトを使用します適切なを得て、各顧客のために、どうですか?これは、2つのステップで行われる必要がある

おかげ

答えて

1

。その後、私はあなたに

Firtsが最後CustomerOldにadderessesを揃えるこの方法をお勧めし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 
0

でこのテーブルを結合して、すべてのCustomersNewレコードを作成

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

:まず、すべてのAddressesレコードを作成アドレス

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 
関連する問題