mysql - 在 MySQL 的父子关系中强制执行 "favorite"的最佳方法是什么?

标签 mysql database foreign-keys

我有一个像这样的父表和子表。

PARENT
id - INT NOT NULL
favoriteChild - NULL DEFAULT NULL

CHILD
id - INT NOT NULL
parent_id - INT NOT NULL

RELATIONSHIPS
parent.favoriteChild -> child.id
child.parent_id -> parent.id

我正在创建一个父级,然后创建一个子级。我有一个触发器设置,以便第一次为给定父级创建子级时,会设置 favoriteChild 的值。

保证被设置为 favoriteChild 的 child 是 parent 的 child 的最佳方法是什么?

我的第一 react 是使用 BEFORE_INSERT 触发器,以便每次修改 favoriteChild 时,首先都会验证它是属于该父项的子项的 ID。

我是否缺少一种更优雅的处理方式?

最佳答案

CREATE TABLE PARENT (
  id INT NOT NULL PRIMARY KEY,
  favoriteChild INT NULL DEFAULT NULL
);

CREATE TABLE CHILD (
  id INT NOT NULL PRIMARY KEY,
  parent_id INT NOT NULL,
  UNIQUE KEY (parent_id, id),
  FOREIGN KEY (parent_id) REFERENCES PARENT(id)
);

ALTER TABLE PARENT ADD FOREIGN KEY (id, favoriteChild) 
  REFERENCES CHILD (parent_id, id);

现在我们证明,当我们插入父级和子级并使该子级成为其父级的最爱时,约束就得到满足:

mysql> insert into parent values (10, null);
Query OK, 1 row affected (0.00 sec)

mysql> insert into child values (1, 10);
Query OK, 1 row affected (0.00 sec)

mysql> update parent set favoriteChild = 1 where id = 10;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

现在我们尝试另一个父级和子级,但让子级引用不同的父级。我们不能让那个 child 成为错误 parent 的最爱。

mysql> insert into parent values (20, null);
Query OK, 1 row affected (0.00 sec)

mysql> insert into child values (2, 10);
Query OK, 1 row affected (0.00 sec)

mysql> update parent set favoriteChild = 2 where id = 20;
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test`.`parent`, CONSTRAINT `parent_ibfk_1` FOREIGN KEY (`id`, `favoriteChild`) REFERENCES `child` (`parent_id`, `id`))

关于mysql - 在 MySQL 的父子关系中强制执行 "favorite"的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59339955/

相关文章:

mysql - SQL Join - 需要解释

mysql - 合并找到的结果和未找到的结果

database - 当在 Node.js 中从 firebird 中选择时,未知值 <Buffer d2 f3 f0 e0 e5 e2 e0 20>

database - go rest api 服务器设计良好实践

c# - 如何自动测试我的数据库驱动功能?

mysql - mysql建表

mysql - 这里不能添加外键吗?

MySQL优化

mysql - 从两个表中选择并按照两个表中公共(public)列的降序排列它们

mysql - SQL 外键约束错误 1215