Reputation: 3260
I need to create multiple many to many relationships in my database.
There is one 'Main' table, lets call it 'projects'.
Then there are 3 tables that contain 'options'.
Let's say we have: category, region and users. The only information these hold are the item's name and an ID.
Multiple categories, regions and users can be assigned to multiple projects.
So I have two options for creating this relationship:
1) Create a relationship table for each 'option' table. Each table would contain two columns: 'project_id' and either category_id, region_id or user_id. Using this method i'd have 3 relationship tables, with each table only handling the relationship between one pair of tables. E.g:
****************************
* project_id * category_id *
****************************
* 1 * 3 *
*------------*-------------*
* 3 * 4 *
*------------*-------------*
2) Create a relationship table with 4 columns project_id, category_id, region_id and user_id. Each row would only have 2 fields being used at any time. The project_id, then the id of field of the item being related.
**************************************************
* project_id * category_id * user_id * region_id *
**************************************************
* 1 * 3 * * *
*------------*-------------*---------*-----------*
* 3 * 4 * * *
*------------*-------------*---------*-----------*
* 3 * * 2 * *
*------------*-------------*---------*-----------*
* 4 * * * 3 *
*------------*-------------*---------*-----------*
I'm tempted by the second option, as it will prevent me needing to create extra relationship tables. Are there any pitfalls or additional problems I should consider?
Upvotes: 6
Views: 2080
Reputation: 839164
Are there any pitfalls or additional problems I should consider?
One of your requirements is "Each row would only have 2 fields being used at any time." In MySQL there is no easy way to enforce this constraint so you could get data inconsistency.
If you use the multiple table design, you can use non-NULL fields and foreign key constraints to ensure consistency.
Upvotes: 5