MYSQL 如何在两列任意组合(双向)上创建 UNIQUE 约束
MYSQL How to create a UNIQUE constraint on two columns any combinations (in both directions)
如果我的 mySQL table 有两行,我如何做一个约束,即相同的值不能同时出现在两个列上,并防止创建任何组合的双打两列?
例如,如果我插入以下内容:
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
很久以前,我在网上找到了这个。
比方说,您有 table,名为 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 ;
注意:根据您的更改 table 和列名称。
如果我的 mySQL table 有两行,我如何做一个约束,即相同的值不能同时出现在两个列上,并防止创建任何组合的双打两列?
例如,如果我插入以下内容:
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
很久以前,我在网上找到了这个。
比方说,您有 table,名为 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 ;
注意:根据您的更改 table 和列名称。