MySQL 中的自引用表字段

Self-Referential Table Fields In MySQL(MySQL 中的自引用表字段)
本文介绍了MySQL 中的自引用表字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,它有一个引用自身的外键".这将非常有用,除非我不确定如何将第一条记录添加到这样的表中.无论我添加什么,我都无法为表本身提供有效的外来"键,目前还没有条目.也许我没有正确地处理这个问题,但我希望这张表代表一些始终是它自身成员的东西.有没有办法引导"这样的表格,或者另一种方法来进行自我引用?

I have a table which has a "foreign key" referencing itself. This would be very useful, except I am uncertain how to add the first record to such a table. No matter what I add, I cannot provide a valid "foreign" key to the table itself, having no entries yet. Maybe I'm not going about this correctly, but I want this table to represent something that is always a member of itself. Is there a way to "bootstrap" such a table, or another way to go about self-reference?

推荐答案

一个选项是让你的字段NULL-able,并将根记录的父键设置为NULL:

One option is to make your field NULL-able, and set the root record's parent key to NULL:

CREATE TABLE tb_1 (
   id       int   NOT NULL  PRIMARY KEY,
   value    int   NOT NULL,
   parent   int   NULL,
   FOREIGN KEY (parent) REFERENCES tb_1(id)
) ENGINE=INNODB;
Query OK, 0 rows affected (0.43 sec)

-- This fails:
INSERT INTO tb_1 VALUES (1, 1, 0);
ERROR 1452 (23000): A foreign key constraint fails.

-- This succeeds:
INSERT INTO tb_1 VALUES (1, 1, NULL);
Query OK, 1 row affected (0.08 sec)

否则,您仍然可以使用 NOT NULL 父键并将其指向根记录本身:

Otherwise you could still use a NOT NULL parent key and point it to the root record itself:

CREATE TABLE tb_2 (
   id       int   NOT NULL  PRIMARY KEY,
   value    int   NOT NULL,
   parent   int   NOT NULL,
   FOREIGN KEY (parent) REFERENCES tb_2(id)
) ENGINE=INNODB;
Query OK, 0 rows affected (0.43 sec)

-- This fails:
INSERT INTO tb_2 VALUES (1, 1, 0);
ERROR 1452 (23000): A foreign key constraint fails.

-- This succeeds:
INSERT INTO tb_2 VALUES (1, 1, 1);
Query OK, 1 row affected (0.08 sec)

这篇关于MySQL 中的自引用表字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)