MYSQL如何在两列上创建任意组合的UNIQUE约束(在两个方向上)

时间:2015-07-25 15:18:30

标签: mysql unique combinations

如果我的mySQL表有两行,我如何制作一个约束,相同的值不能同时在两个列上并防止创建两列任何组合的双精度数?

例如,如果我插入以下内容:

col1    col2
a       b   ok
c       a   ok
c       b   ok
c       a   not ok sure it's already in the table
a       c   not ok because it's already in the table in other combination (c a)
f       f   not ok because same value in both columns

1 个答案:

答案 0 :(得分:0)

很久以前,我在网上发现了这个。

假设您有一个名为tableName的表,那么您必须创建一个包含两列的主键。

create table tableName
(
    col1 int not null,
    col2 int not null,
    primary key (col1,col2)
);

但是创建主键并不能解决您的问题,反之亦然。为此,您必须创建trigger,以检查双方的唯一性。

DELIMITER $$
CREATE TRIGGER tableName_bi BEFORE INSERT ON tableName FOR EACH ROW 
BEGIN 
    DECLARE found_count,newcol1,newcol2,dummy INT;
    SET newcol1 = NEW.col1;
    SET newcol2 = NEW.col2;
    SELECT COUNT(1) INTO found_count FROM tableName
    WHERE col1 = newcol2 AND col2 = newcol1;
    IF found_count = 1 THEN
        SELECT 1 INTO dummy FROM information_schema.tables;
    END IF;
END; $$ 
DELIMITER ;

注意:根据您的名称更改您的表名和列名。