我想要的是在 mysql 表中插入数据,但我无法找到从一行建立关系的方法
假设我有一个文件file.tab它包含类似的数据
parent_1 parent_details_1 child_1.1 child_details_1.1 child_1.2 child_details_1.2
parent_2 parent_details_2 child_2.1 child_details_2.1
parent_3 parent_details_3 child_3.1 child_details_3.1 child_3.2 child_details_3.2 child_3.3 child_details_3.3
我想要实现的是将数据插入两个表中,例如
parent_table
+---+-----------+-------------------+
|id | name | details |
+---+-----------+-------------------+
| 1 | parent_1 | parent_details_1 |
| 2 | parent_2 | parent_details_2 |
| 3 | parent_3 | parent_details_3 |
+---+-----------+-------------------+
child_table
+---+-----+-----------+-------------------+
|id | pid | name | details |
+---+-----+-----------+-------------------+
| 1 | 1 | child_1.1 | child_details_1.1 |
| 2 | 1 | child_1.2 | child_details_1.2 |
| 3 | 2 | child_2.1 | child_details_2.1 |
| 4 | 3 | child_3.1 | child_details_3.1 |
| 5 | 3 | child_3.2 | child_details_3.2 |
| 6 | 3 | child_3.3 | child_details_3.3 |
+---+-----+-----------+-------------------+
前两列属于父母,之后两两列属于孩子,但我不知道父母有多少个孩子。
我尝试过以这种方式加载文件。
LOAD DATA INFILE '/tmp/file.tab INTO TABLE ...
但接下来我该怎么办我不知道。
请帮助我解决这个问题。
创建一个表(Staging
)有很多列。有空(NULL
) 列parent_id
以及孩子们的身份证。
希望“短”行能够在缺失的子列中放置空值LOAD DATA
.
INSERT .. SELECT ..
得到parent
and parent_detail
进入Parents
桌子。拉回ids
from Parents
into Staging.parent_id
。有关这两个 SQL 的详细信息,请参见http://mysql.rjweb.org/doc.php/staging_table#normalization http://mysql.rjweb.org/doc.php/staging_table#normalization
现在对每个可能的“子”列集执行类似的操作:child1
and child1_detail
(可能是 NULL 对)和当前的 NULLchild1_id
。 child2* 等也是如此。请注意,填充时Children
表,你已经有了parent_id
可用的。
这是执行任务的全 SQL 方式。它只比编写 Perl/PHP/Java/VB/任何代码来完成任务稍微简单一些。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)