【发布时间】:2014-12-11 10:52:22
【问题描述】:
使用 mySQL,我有这些表:
Person
----------
id (PK)
name
...
Person_Association
----------
id_Person1 (FK Person.id)
id_Person2 (FK Person.id)
我希望每个 Person_Association 都是唯一的:如果 (#1, #2) 存在,则 (#1, #2) 和 (#2, #1) 都不能插入。
为此,我向 Person_Association 添加了一个字段和一个触发器,如下所示:
Person_Association
----------
id_Person1 (FK Person.id)
id_Person2 (FK Person.id)
unique_id (PK)
CREATE TRIGGER `Person_Association_BINS` BEFORE INSERT ON `Person_Association` FOR EACH ROW
BEGIN
IF (new.id_Person1 < new.id_Person2) THEN
SET new.unique_id = CONCAT(new.id_Person1, '-', new.id_Person2);
ELSE
SET new.unique_id = CONCAT(new.id_Person2, '-', new.id_Person1);
END IF;
END
它有效,但有更好的方法吗?
【问题讨论】: