[英]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.