Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combination of two columns unique constraint

I created the table t1t2 which connects tables t1 and t2 as follows:

CREATE TABLE t1t2(
id integer primary key,
t1_id integer,
t2_id integer,
foreign key(t1_id) references t1(id),
foreign key(t2_id) references t2(id));

Is it possible to define a constraint (restriction) that enables only unique values of tuple (t1_id, t2_id)? Or should I check this in the application?

like image 656
xralf Avatar asked May 08 '12 15:05

xralf


2 Answers

 CREATE UNIQUE INDEX idx_twocols ON t1t2(t1_id, t2_id)

You will probably need to add NOT NULL to the declarations for each of the two columns.

Alternatively, you could choose to forego the primary key column (if all you're using it for is uniqueness) and create the primary key on the combination of t1_id and t2_id:

CREATE TABLE t1t2(
t1_id integer NOT NULL,
t2_id integer NOT NULL,
PRIMARY KEY (t1_id, t2_id),
foreign key(t1_id) references t1(id),
foreign key(t2_id) references t2(id));

The PRIMARY KEY is a special case of a UNIQUE index. Using the composite PRIMARY KEY saves you one column and one index, but requires your application to know both t1_id and t2_id to retrieve a single row from the table.

like image 154
Larry Lustig Avatar answered Jan 02 '23 00:01

Larry Lustig


You can add a unique constraint to your create table statement. This does not have to be the primary key.

UNIQUE(t1_id, t2_id),
like image 43
Banjocat Avatar answered Jan 02 '23 01:01

Banjocat