Pergunta

ALTER TABLE `test` ADD UNIQUE (
`a` ,
`b`
);

I want that after creating this unique key, it won't be possible to add B,A.

For example: "Michael", "Jackson", won't allow inserting later "Jackson", "Michael".

Foi útil?

Solução

I'm going to assume you're application deals with something besides real names. (Because "Jackson Michael" is a legitimate name in English. So are "John David" and "David John".)

The simplest way is to use a CHECK() constraint to enforce alphabetical order between the two columns.

alter table test
add constraint test_alpha_order
check (a < b);

But note that you might run into problems with case sensitivity, too. That is, your dbms might believe that {'Jackson', 'Michael'} and {'jackson', 'michael'} are two different, valid values. If case sensitivity is a problem, the most common solution I've seen is to enforce lowercase values, like this.

alter table test
add constraint test_alpha_order
check (a = lower(a) and
       b = lower(b) and
       a < b );

Outras dicas

Related to my comment about lack of check constraints in MySQL, a well known workaround has been the trigger. You would do the following check as part of an BEFORE INSERT ON trigger:

SELECT COUNT(*) from mytable WHERE b=NEW.a and a=NEW.b

but to make this cause a failure, you have to resort to MySQL Trickery 1.0 (previously described in TRIGGERs that cause INSERTs to fail? Possible?)

So, you would need something like the following: (tested)

delimiter |
CREATE TRIGGER t1
BEFORE INSERT ON mytable
FOR EACH ROW
BEGIN
      set @x = (SELECT COUNT(*) FROM mytable WHERE b=NEW.a and a=NEW.b);
      IF (@x > 0) THEN
         set @y = (SELECT noSuchField FROM mytable);
      END IF;
END;
|

NOTE: I'm ignoring case insensitivity here -- your question doesn't seem to require that.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top