以下可能不是最佳选择,因为它提供了一种非常规的方法来标记最喜欢的物品。不过,这样做的好处是,您将只有两张没有循环引用的表,并且可以保证每个人都拥有不超过一个最喜欢的物品。
所以,这是两个表,people
(或persons
)和belongings
。该people
表具有以下结构:
person_id INT AUTO_INCREMENT,
other columns as necessary,
PRIMARY KEY (person_id)
该belongings
表是这样创建的:
belonging_id INT AUTO_INCREMENT,
person_id INT NOT NULL,
is_favourite enum ('1'),
other columns as necessary,
PRIMARY KEY (belonging_id),
FOREIGN KEY (person_id) REFERENCING people (person_id),
UNIQUE (person_id, is_favourite)
关键元素声明为具有单个可能值is_favourite
的可空值。enum
这样,当您在 的对上声明唯一约束时(person_id, is_favourite)
,您可以拥有尽可能多的相同person_id
且为空 (null)is_favourite
的行,因为唯一约束忽略至少一个成员为空的行。而且您将无法创建多个person_id
with is_favourite = '1'
,因为这会违反唯一约束。