I'm referring to this SO-question. Here, in the first answer, it's said that
UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to speed up queries, UNIQUE indexes can be used to enforce restraints on data, because the database system does not allow this distinct values rule to be broken when inserting or updating data.
As my english is not the best, I wonder what it means, that
the same row may not have identical non-NULL values for all columns in this index as another row
To quickly connect this with my acutal problem, here is my scenario. I have three tables
game(gameID, ...), PK(gameID)
player(gameID, playerName, ...), PK(gameID, playerName), FK(gameID)
prop(gameID, playerName, c1, c2, c3, ...) PK(gameID, playerName), FK(gameID, playerName)
Now, a player connected to a game can choose 1-n props. In such a prop, c1 - c3
are representing playing card values, more exact {1,2,3, ..., T, J, Q, K, A}.
Such a combination of three cards can consist of same values, but a combination can only be choosen once in a game. E.g. a player can choose {2,2,3}
and {A,2,3}
, but then, in that game, no other player can pick the same combination again.
Now to return on my preamble, the three elements c1, c2, c3
are not declared UNIQUE
in the CREATE TABLE
statement (otherwise the first combination in the example would not be possible). Does that mean I cannot use UNIQUE(gameID, c1, c2, c3)
as a constraint to assure uniqueness of a combination in a game? Is this a good example to use INDEX(gameID, c1, c2, c3)
? What is the difference in using the two variants in my particular case?
Finally the CREATE TABLE
statement of that third table would be
create table prop(
gameID INTEGER NOT NULL,
playerName VARCHAR(25) NOT NULL,
isBB BOOLEAN NOT NULL DEFAULT FALSE,
card1 VARCHAR(1) NOT NULL,
card2 VARCHAR(1) NOT NULL,
card3 VARCHAR(1) NOT NULL,
PRIMARY KEY (gameID, playerName),
FOREIGN KEY (gameID, playerName) REFERENCES player(gameID, playerName) ON DELETE CASCADE,
UNIQUE(gameID, c1, c2, c3) /* OR INDEX(gameID, c1, c2, c3)?
)ENGINE=INNODB;