Question

Suppose I have a "game" table with an ordered pair of 2 participants:

id | make | party1_id | party2_id

Now I want to fill the table like this:

INSERT INTO game (party1_id, party2_id) VALUES (1, 2); -- OK
INSERT INTO game (party1_id, party2_id) VALUES (4, 3); -- OK
INSERT INTO game (party1_id, party2_id) VALUES (2, 4); -- OK
INSERT INTO game (party1_id, party2_id) VALUES (2, 1); -> should fail

The last attempt is supposed to fail, because the game with the two participants already exists, albeit with a different player order. I can't force the table to hold the party1_id and party2_id in the order of the ids, since there is some meaning to them (home player versus away).

So the question is, can we create a UNIQUE constraint in MySQL the would work for my case?

So far I think I could create a generated column with both ids in ascending order as concatenated strings and put a unique index on them (E.g. "1_2" for the first row). This however is a bit awkward it seems.

I saw another question related to this, but it is not for MySQL.

Was it helpful?

Solution

I wonder if this trigger will do the trick:

CREATE TABLE game(
party1_id INTEGER,
party2_id INTEGER,
CONSTRAINT p12_unique UNIQUE (party1_id, party2_id));

CREATE TRIGGER no_way BEFORE insert ON game
BEGIN
  SELECT RAISE(ABORT, 'There can be only one.')
  WHERE EXISTS (SELECT 1
                  FROM game
                  WHERE 
                  party1_id = new.party2_id AND 
                  party2_id = new.party1_id);
END;


/* Create few records in this table */
INSERT INTO game (party1_id, party2_id) VALUES (1, 2);
INSERT INTO game (party1_id, party2_id) VALUES (4, 3);
INSERT INTO game (party1_id, party2_id) VALUES (2, 4);
INSERT INTO game (party1_id, party2_id) VALUES (1, 2); /* fail */
INSERT INTO game (party1_id, party2_id) VALUES (2, 1); /* fail */
INSERT INTO game (party1_id, party2_id) VALUES (4, 2); /* fail */

COMMIT;

/* Display all the records from the table */
SELECT * FROM game;

It was tested in sqlite because I didn't have a mysql machine handy... I hope it works in mysql.

Best...

p.s. see you on Thursday!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top