Lukas_Skywalker
Lukas_Skywalker

Reputation: 2070

Unique constraint based on associated column value

I have the following (simplified) data structure:

Property                    Product
-----------   n <----> 1    -------
product_id                  manufacturer
type                        name
value                    

Where the products table might look like this

| name         |
|--------------|
| iPad 2       |
| iPhone 6     |

and the associated properties might be

| product_id | type        | value |
|----------------------------------|
|      1     | RAM         | 16GB  |
|      1     | CPU         | A11   |
|      1     | Screen Size | 10"   |
|      2     | Cellular    | yes   |
|      2     | Screen Size | 5.5"  |

Is it possible, in MySQL, to create a constraint, so that every product can have each property type at most once (e.g., a product can't have multiple Screen Sizes associated. As far as I could understand the MySQL docs, constraints only work on one relation, but not across relations.

Upvotes: 1

Views: 36

Answers (1)

Lukas_Skywalker
Lukas_Skywalker

Reputation: 2070

I realized the solution immediately after posting this question. The constraint can be placed on the properties relation, so that each pair of product_id, type can only exist once.

Upvotes: 3

Related Questions