如果我的 mySQL 表有两行,我怎样才能做出一个约束,即相同的值不能同时出现在两个列上,并防止创建两列的任意组合的 double ?
例如,如果我插入以下内容:
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
最佳答案
很久以前,我在网上发现了这个。
假设您有一个名为 tableName
的表,那么您必须创建一个包含这两列的主键。
create table tableName
(
col1 int not null,
col2 int not null,
primary key (col1,col2)
);
但是创建主键并不能解决检查反之亦然组合的问题。为此,您必须创建一个触发器来检查双方的唯一性。
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 ;
注意:根据您的需要更改表和列名称。
关于MYSQL 如何对两列任意组合(双向)创建UNIQUE约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31627993/