Pregunta

I have a table where I use a composite key as primary key. Its created something like:

CREATE TABLE FOO(
    BAR1 INT,
    BAR2 INT,
PRIMARY KEY (BAR1, BAR2)) 

BAR1 and BAR2 are FK:s for other tables and I would like to make sure there is always zero or one tuples in my FOO table where both those keys exist at the same time. Basicaly I would like it at the same time to be like:

PRIMARY KEY (BAR2, BAR1)

At the same time the keys must both be allowed to be paired an arbitrary number of times with other keys so they cannot each of them be unique.

So when I have done

INSERT INTO FOO VALUES (1,2); 

the schema would disallow

INSERT INTO FOO VALUES (2,1);

What is a good way to solve this in mysql?

¿Fue útil?

Solución

A possible solution is to use a trigger.

create trigger bi_foo before insert on foo
for each row
begin
  if exists(select 1 from foo where bar1 = NEW.bar2 and bar2 = NEW.bar1)
  then
    signal sqlstate '50000' set message_text="Oops";
  end if;
end

This will work:

insert into foo values (1, 2), (3, 4), (5, 6);
insert into foo values (3, 2), (3, 5), (1, 6);

This will fail:

mysql> insert into foo values (2, 1);
ERROR 1644 (50000): Oops

Otros consejos

I'm not sure I've understood your requirement but I think you will want one of the following.

  1. Ensure that only one possible pairing of BAR1/BAR2 values can exist in FOO:

    CREATE TABLE FOO(
        BAR1 INT,
        BAR2 INT,
    CHECK (BAR1<=BAR2),
    PRIMARY KEY (BAR1, BAR2));
    
  2. Ensure that both pairings must always exist:

    CREATE TABLE FOO(
        BAR1 INT,
        BAR2 INT,
    FOREIGN KEY (BAR2, BAR1) REFERENCES FOO (BAR1, BAR2),
    PRIMARY KEY (BAR1, BAR2));
    
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top