many to many relationship

前端 未结 2 1400
被撕碎了的回忆
被撕碎了的回忆 2021-01-06 05:02

If I have two tables - table beer and table distributor, each one have a primary key and a third table that have the foreign keys and calls beer_

相关标签:
2条回答
  • 2021-01-06 05:08

    I would put a primary key in the join table beer_distributor, not a dual primary key of the two foreign keys. IMO, it makes life easier when maintaining the relationship.

    UPDATE

    To emphasize this point, consider having to change the distributor ACOO9 for beer 163. With the dual primary key, you'd have to remove then reinsert OR know both existing values to update the record. With a separate primary key, you'd simply update the record using this value. Comes in handy when building applications on top this data. If this is strictly a data warehouse, then a dual primary key might make more sense from the DBA perspective.

    UPDATE beer_distributor SET distributor_id = XXXXX WHERE beer_id = 163 AND distributor_id = AC009
    

    versus

    UPDATE beer_distributor SET distributor_id = XXXXX WHERE id = 1234
    
    0 讨论(0)
  • 2021-01-06 05:26

    You've definitely got the right idea. Your beer_distributor table is what's known as a junction table. JOINs and keys/indexes are used together. The database system uses keys to make JOINs work quickly and efficiently. You use this junction table by JOINing both beer and distributor tables to it.

    And, your junction table should have a primary key that spans both columns (a multiple-column index / "composite index"), which it looks like it does if I understand that diagram correctly. In that case, it looks good to me. Nicely done.

    0 讨论(0)
提交回复
热议问题