假设我有一个包含两列的mysql表:A和B.是否可以有一个唯一键,这样我只能在A或B(一次在整个表中)中只插入一次值?整个mysql表的唯一键?
因此,如果列A包含'qwe'且B包含'asd',那么这两个值不能再插入任一列中。
这是行不通的:
UNIQUE KEY `A` (`A`,`B`),
UNIQUE KEY `A_2` (`A`),
UNIQUE KEY `B` (`B`),
UNIQUE KEY `B_2` (`B`,`A`)
感谢。
编辑:我可以用下面的触发器来实现:
delimiter |
create trigger unique_check before insert on mytable
for each row begin
declare alreadyexists integer;
select count(*) > 0 into alreadyexists from mytable
where A=NEW.B or B=NEW.A;
IF alreadyexists = 1 THEN begin
DECLARE dummy INT;
SELECT 'A OR B already exists' INTO dummy FROM mytable
WHERE nonexistent = 'value';
end;
END IF;
END;|
不过,我没有看到 'A或B已经存在' 错误消息,但:
ERROR 1054(42S22):'where子句'中未知列'不存在'
再次感谢!
另一种选择可能是使用一个带'a'和'b'位的列'value','a','b'的表格,然后当值(必须是唯一的)被输入时也设置a或b为1.我想这仍然给出了如果某人为'a'和'b'放入1的问题,但这是另一种方式 – Harold 2011-03-15 11:21:45