在MySQL的父子关系中强制执行“收藏夹”的最佳方法是什么?

问题描述 投票:-1回答:1

我有这样的父子表。

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的值。

保证被设置为收藏儿童的孩子是父母的孩子的最佳方法是什么?

我的本能是使用BEFORE_INSERT触发器,以便在每次修改favouriteChild时,都首先将其验证为与该父项有关的孩子的ID和ID。

我是否错过了一种更优雅的处理方式?

mysql database foreign-keys
1个回答
0
投票
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

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

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`))
© www.soinside.com 2019 - 2024. All rights reserved.