如何让两个外键独一无二?

时间:2013-06-19 02:27:31

标签: mysql unique one-to-one

我有两张桌子。

MY_ENTITY
----------------------------------------------------
ID               BIGINT                (PK)
YOUR_ENTITY_ID_1 BIGINT    NOT NULL    (FK) OneToOne ||--|
YOUR_ENTITY_ID_2 BIGINT        NULL    (FK) OneToOne ||--|
                                                         |
YOUR_ENTITY                                              |
----------------------------------------------------     |
ID               BIGINT                (PK) -------------|

我想我可以使每个YOUR_ENTITY_ID_X列都是唯一的。

如何确保所有YOUR_ENTITY列中只有一个YOUR_ENTITY_ID_X

1 个答案:

答案 0 :(得分:1)

使用触发器这样做有点hackish。

表格结构:

CREATE TABLE MY_ENTITY (
    id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    ENTITY_ID_1 INT UNSIGNED UNIQUE,
    ENTITY_ID_2 INT UNSIGNED UNIQUE,
    UNIQUE(ENTITY_ID_1, ENTITY_ID_2)
);

触发器,会阻止插入:

DROP TRIGGER IF EXISTS ONLY_UNIQUE_ENTITIES;
DELIMITER //
CREATE TRIGGER ONLY_UNIQUE_ENTITIES BEFORE INSERT ON `MY_ENTITY`
FOR EACH ROW
BEGIN
    DECLARE entity_exists INT DEFAULT 0;
    SELECT 
        COUNT(*) INTO entity_exists
    FROM 
        `MY_ENTITY` 
    WHERE 
        (`ENTITY_ID_1` IN (NEW.ENTITY_ID_1, NEW.ENTITY_ID_2)) 
      OR
        (`ENTITY_ID_2` IN (NEW.ENTITY_ID_1, NEW.ENTITY_ID_2));
    IF entity_exists THEN
        SET NEW.ENTITY_ID_1 = NEW.ENTITY_ID_2;
    END IF;     
END;