Suppose I have a mysql table with two columns: A and B. Is it possible to have a unique key so that I can only insert a value only once in either A or B (once in the whole table)?
So if column A contains 'qwe' and B contains 'asd' then these two values cannot be inserted anymore in either column.
this will not work:
UNIQUE KEY `A` (`A`,`B`),
UNIQUE KEY `A_2` (`A`),
UNIQUE KEY `B` (`B`),
UNIQUE KEY `B_2` (`B`,`A`)
thanks.
edit: I was able to accomplish this with the following trigger:
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;|
However, I do not see the 'A OR B already exists' error message, but:
ERROR 1054 (42S22): Unknown column 'nonexistent' in 'where clause'
Thanks again!