我想要的是在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
Run Code Online (Sandbox Code Playgroud)
我想要实现的是在两个表中插入数据
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 |
+---+-----+-----------+-------------------+
Run Code Online (Sandbox Code Playgroud)
前两列用于父级,之后两列属于子级,但我不知道父级有多少子级.
我试图以这种方式加载文件.
LOAD DATA INFILE '/tmp/file.tab INTO TABLE ...
Run Code Online (Sandbox Code Playgroud)
但我接下来做什么我不知道.
所以请在这个问题上帮助我.
创建一个Staging包含大量列的表().为子节点设置empty(NULL)列parent_id和id.
希望'短'行将在遗留的子列中放置空值LOAD DATA.
INSERT .. SELECT ..进入parent和parent_detail进入Parents表.拉回ids从Parents成Staging.parent_id.有关这两个SQL的详细信息,请参见http://mysql.rjweb.org/doc.php/staging_table#normalization
现在为每个可能的"子"列集做类似的事情: child1和child1_detail(可能是NULL对)和当前的NULL child1_id.同样适用于child2*等.请注意,填充Children表格时,您已经可以parent_id使用.
这是执行任务的全SQL方式.它只比编写Perl/PHP/Java/VB /任何代码来执行任务稍微麻烦一些.