How can I efficiently create a unique index on two fields in a table like this: create table t (a integer, b integer);
where any unique combination of two different
I think this can only be done using a FOR INSERT trigger (in combination with a unique constraint on the two columns). I'm not really fluent in MySql syntax (my T-SQL is better), so I guess the following will contain some errors:
Edit: Cleaned up the syntax so it works for MySQL. Also, note you'll probably want to put this as a BEFORE UPDATE trigger too (with a different name of course).
Also, this method relies on having a primary or otherwise unique key on the two fields (ie. this trigger only checks the reverse doesn't already exist.) There doesn't seem to be any way of throwing an error from a trigger, so I dare say this is as good as it gets.
CREATE TRIGGER tr_CheckDuplicates_insert
BEFORE INSERT ON t
FOR EACH ROW
BEGIN
DECLARE rowCount INT;
SELECT COUNT(*) INTO rowCount
FROM t
WHERE a = NEW.b AND b = NEW.a;
IF rowCount > 0 THEN
-- Oops, we need a temporary variable here. Oh well.
-- Switch the values so that the key will cause the insert to fail.
SET rowCount = NEW.a, NEW.a = NEW.b, NEW.b = rowCount;
END IF;
END;