patternsqlMinor
Make two columns unique both ways
Viewed 0 times
uniquecolumnswaysmakebothtwo
Problem
I'm creating a database which stores football matches.
Each round, any given football club may only play once (home or away).
For example, after the insert of
inserts such as
must be forbidden since Barcelona has already played one match against Real in Round 1. They shouldn't be able to play against Bayern in the same round (doesn't matter if they're playing home or away).
How can I ensure such inserts don't happen?
Do I use a trigger? Some sort of unique index combination? I've tried both but got lost and didn't actually get the outcome expected.
Thanks
Each round, any given football club may only play once (home or away).
For example, after the insert of
INSERT INTO Match (Round, Home, Away) VALUES (1, Barcelona, Real);inserts such as
INSERT INTO Match (Round, Home, Away) VALUES (1, Bayern, Barcelona);INSERT INTO Match (Round, Home, Away) VALUES (1, Barcelona, Bayern);must be forbidden since Barcelona has already played one match against Real in Round 1. They shouldn't be able to play against Bayern in the same round (doesn't matter if they're playing home or away).
How can I ensure such inserts don't happen?
Do I use a trigger? Some sort of unique index combination? I've tried both but got lost and didn't actually get the outcome expected.
Thanks
Solution
With 2 unique constraints you can achieve the desired restriction :
Check the fiddle here
create unique index on match (round, least(home, away));
create unique index on match (round, greatest(home, away));Check the fiddle here
Code Snippets
create unique index on match (round, least(home, away));
create unique index on match (round, greatest(home, away));Context
StackExchange Database Administrators Q#320513, answer score: 4
Revisions (0)
No revisions yet.