tags:

views:

155

answers:

3

I'm useing MySQL and I have three tables, a table of tasks, a table of products and a table that describes the relation between the two: Each product is composed of several tasks, and each task may be found in multiple products.

The table that describes the relationship between the two has two primary keys, ProductID and TaskID that are both foreign keys as well. In this table I have a field called TaskOrder that for a given Product lists the order that tasks must be performed.

What I want is to say that for any product you can't have two tasks with the same TaskOrder, however I can't just set TaskOrder to unique because diffrent products will (and should) have duplicate values for TaskOrder

Is there some way to do this?

A: 

The junction table has one primary key, but it's a multi-field key with two fields (the two FK's for the other tables). A PK doesn't need to be only one field.

le dorfier
+5  A: 

You want a UNIQUE constraint:

create table ProductTasks
 ( ProductID ...
 , TaskId ...
 , TaskOrder ...
 , primary key (ProductId, TaskId)
 , unique (ProductId, TaskOrder)
 );
Tony Andrews
interesting DDL formatting.. I actually kind of like it :)
roe
Thank you very much, also I think I might adopt your formating, dose is there a layout guide somewhere? I'm wondering how it would work on, say, and insert statement with more than one entry.
Benjamin Confino
SQL layout is a matter of personal taste and/or local standards. I like the prefixed commas as they are a bit like "bullet points" and it's easy to see that none are missing or superfluous. Some people detest thus style, saying (reasonably) that commas belong AFTER something, not before!
Tony Andrews
+2  A: 

Create a unique index on the combination of the two fields ProductID and TaskOrder by adding the following to the table creation command:

CONSTRAINT UNIQUE (ProductID, TaskOrder)
David Hanak