I apologise for the confusing title but I’m really not sure how to describe this problem in one sentence.
I have an SQLite database for a generalised tipping competition. For those unfamiliar with the concept, people “tip” who they think will win in each match of each round of a sporting competition, and the person with the most correct tips at the end of the competition wins (the prize may be money, pride, etc). It’s very popular in Australia with the AFL.
The basic structure is that users register as an owner, and they can then create as many competitions as they want, and each competition is linked to them with a foreign key. This is the relevant part of the database schema:
create table owner (
owner_id INTEGER NOT NULL,
owner_name VARCHAR NOT NULL,
owner_nick VARCHAR UNIQUE NOT NULL,
owner_email VARCHAR NOT NULL,
owner_password VARCHAR NOT NULL,
CONSTRAINT owner_pk PRIMARY KEY (owner_id)
);
create table comp (
comp_id INTEGER NOT NULL,
comp_owner_id INTEGER NOT NULL,
comp_name VARCHAR UNIQUE NOT NULL,
CONSTRAINT comp_pk PRIMARY KEY (comp_id),
CONSTRAINT comp_owner_fk FOREIGN KEY (comp_owner_id) REFERENCES owner (owner_id) NOT DEFERRABLE
);
The gist of the problem is this: I want to enforce a unique constraint on the comp_name field of the comp table (as shown above) because a single owner shouldn’t have two or more competitions with the same name. However, it is entirely possible that two different owners would want two different competitions with the same name (for example, two offices running tipping competitions for the same sporting league). Is it possible to enforce this using SQL, or do I need to do the enforcement manually elsewhere?
A few notes:
- I’m using SQLite 3.6.20, which has proper foreign key constraint enforcement
- The database will never be used in a production level application. It’s a private project.
- The database is being used in a web-based PHP application.
- If this cannot be achieved with SQLite, can it be achieved with MySQL?
EDIT: I feel I should point out that I’m aware SQLite has very limited alter table support, and deleting the database and starting over is very much an option.
Just create a
UNIQUEconstraint on those two fields, like so:that should do what you want.