1

我有两张桌子。

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列中只有一个?

4

1 回答 1

1

使用触发器有点骇人听闻的方式。

表结构:

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;
于 2013-06-19T04:38:49.060 回答