简体   繁体   English

自引用表,单个查询中的父/子插入语句

[英]Self-referencing table, parent/child insert statement in a single query

I have a self-referencing table, and I am wanting add both the parent and child examples in a single query. 我有一个自引用表,我想在一个查询中添加父和子示例。 Is there a better way to do it then to break it down in a fashion similar to what I have below? 有没有更好的方法来做到这一点,以类似于我下面的方式分解它?

+---------------------+
|       example       |
+---------+-----------+
|   id    | parent_id |
+---------+-----------+
|    1    |           |
|    2    |     1     |
|    3    |     1     |
|    4    |     1     |
|    5    |           |
|    6    |     5     |
|    7    |     5     |
+---------+-----------+

DECLARE example_id INT;

INSERT INTO `example` (parent_id) VALUE("");

SET example_id = LAST_INSERT_ID();

INSERT INTO `example` (parent_id) VALUE (example_id);

If you are referring to tree structure with your question you should better check this article . 如果您在提到树形结构时提​​出问题,最好查看这篇文章 If you would only have 1 level of children for parent then your way is possibly the simplest way around. 如果您只有1级孩子的父母,那么您的方式可能是最简单的方法。

Your way of doing things looks OK. 你做事的方式看起来不错。
In a real-world example you'll probably do an insert - select based on some criteria. 在实际示例中,您可能会执行insert - select根据某些条件进行insert - select

INSERT INTO example SELECT 
  null as id 
  ,e.id as parent_id
  ,10 as field1
  ,....
FROM example e WHERE e.somefield = 10 ORDER BY e.id DESC LIMIT 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM