Search code examples
mysqlforeign-keysprimary-keydatabase-normalization

Mysql Intermediate Table- Better to Have Repeating rows?


In a database, I have a username table and I have jurisdiction table. I also have intermediate table to assign a user to one or more jurisdictions.

user table
--------------
userID
first_name
jurID

jurisdiction table
-----------------
jurId
region

user_jurisdiction
------------------
userID 
jurID

This would lead to something like:

 user_jurisdiction
    +--------+-------+
    | userID | jurID |
    +--------+-------+
    |      6 |     2 |
    |      6 |     3 |
    |     11 |     2 |
    |     12 |     1 |
    +--------+-------+

For users that have more than 1 jurisdiction, would this be ok to have repeated userdID rows? or would it be better to have extra JurID columns and have them set as null if not used? such as:

user_jurisdiction
+--------+-------++--------+-------+
| userID | jurID |  jurID | jurID  |
+--------+-------++--------+-------+
|      6 |     2 |       3|    null|
|     11 |     2 |    null|    null|
|     12 |     1 |    null|    null|
+--------+-------+--------+--------+

Solution

  • You have a user_jurisdiction table because you have a many-to-many relationship between users and jurisdictions.

    So, have multiple rows in user_jurisdiction for a single user, one row per jurisdiction:

    6   2
    6   3
    11  2
    12  1
    

    For your example.

    Also, you should include an auto-incrementing UserJurisdictionId in that table. It is a good idea for every table to have a primary key.

    And, you can remove user.jurID from the user table. All information about jurisdictions should be in user_jurisdictions. You would use a join to get the jurisdiction information for a particular user.