簡體   English   中英

MySQL數據庫根據條件從另一個表插入值

[英]MySql database inserting values from another table based on conditions

我用大約100 k的記錄拆分舊表時遇到了一些麻煩。 表用於從電子商務應用程序收集訂單。 每個訂單都作為新行添加到表中。

名為“ customer_informations”的表描述如下:

+-------+-----------------------+------------+---------------------+---------------------+----------------+
| id    | customer_phone_number | first_name | last_name           | address             | order_number   |
+-------+-----------------------+------------+---------------------+---------------------+----------------+

如前所述,每一行都是單獨的順序。 有很多回頭客。 我正在重建結構,因此我選擇了根據customer_phone_number不同的行,並將結果插入到test_informations中,如下所示:

+------+---------------------+------------+-----------+-------------+
| id   | created_at          | first_name | last_name | phone       |
+------+---------------------+------------+-----------+-------------+

該表代表客戶帳戶。 Id字段的值將從原始表復制過來。 現在,我想收集客戶在customer_informations表中擁有的所有地址。

包含客戶地址的表如下所示:

+----+----------+----------+------+-------+-----+-------------------------+
| id | address1 | address2 | city | state | zip | customer_information_id |
+----+----------+----------+------+-------+-----+-------------------------+

這是我的問題所在。 我想從customer_information表中選擇所有不同的地址,並將它們連接到我的test_informations表中(通過customer_information_id外鍵)。 我該如何處理?

我嘗試了以下語句:

INSERT INTO `la`.`test_addresses`
(
`created_at`,
`address1`,
`address2`,
`city`,
`zip`,
`state`,
`customer_information_id`)

Select 
STR_TO_DATE(order_placed, '%m/%d/%y %T') AS created_at,
`address`,
'',
`city_state_zip`,
`zip`,
`state`,
IF( EXISTS( SELECT `id` FROM `test_informations` WHERE `customer_info`.`id` = `test_informations`.`id`),
`customer_info`.`id`,
(SELECT `test_informations`.`id` FROM `test_informations` WHERE `test_informations`.`phone` = `customer_info`.`customer_phone_number`)) 
as customer_information_id 
From `customer_info` group by `address`

所以我正在處理舊表中的每一行。 如果當前行的id在我的temp_informations中,則只需添加此地址,並將外鍵設置為temp_informations條目的id。 如果我當前正在處理的行的id不在test_informations中,則意味着它必須是備用地址,我需要將其連接到該帳戶。 最重要的是,錯誤條件使整個查詢變為無限。

我並不是在為這個問題尋找確切的答案(盡管會很好)。 你們能指出我正確的方向嗎,我應該在哪里尋找答案,我應該研究MySql的哪些功能,或者有關如何高效地拆分表的一些信息?

編輯:

可視化的表不是實際表的精確副本(它們具有更多字段,但為簡單起見,我包括了最重要的字段)。

為什么要使用兩個表(test_informations和另一個用於地址數據)? 我認為最好將所有數據放在一個表中,除非一個用戶有許多城市,州,郵政編碼...

使用一對一的關系還不錯,但是這里我們有兩個表用於同一個實體,我認為您使用的不是很好的方法。 因此,只需合並它,然后就不必通過外鍵來實現它。

如果您有一些可能導致問題的屬性,則可以分別對其進行標准化。

另外,請注意同一輸入的不同變化,例如在驗證之前從電話號碼中清除“-”,“ /”和空格字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM