gpt4 book ai didi

MySql数据库根据条件从另一个表插入值

转载 作者:行者123 更新时间:2023-11-30 00:11:19 26 4
gpt4 key购买 nike

我在拆分包含大约 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 和另一个表用于地址数据)?我认为最好将所有数据放在一张表中,除非一个用户有许多城市、州、邮政编码...

使用一对一关系并不是那么糟糕,但是这里我们有同一实体的两个表,我认为您使用的方法不太好。因此,只需合并它,然后您就不必通过外键来实现它。

如果您有一些可能会导致问题的属性,您可以单独对它们进行规范化。

此外,请注意同一输入的不同变体,例如在验证之前清除电话号码中的“-”、“/”和空格字符。

关于MySql数据库根据条件从另一个表插入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24026958/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com