Under what condition we need to use composite keys in database

前端 未结 4 1661
慢半拍i
慢半拍i 2021-02-09 19:17

i have seen that we can have composite keys where the primary key is made up from combined primary keys of two tables.

Like persons and Books

person_id a         


        
4条回答
  •  隐瞒了意图╮
    2021-02-09 20:11

    I cannot think of any conditions under which you NEED to use composite key. Some of the arguments Pro using a single id column include:
    1. better indexing
    2. simpler joins
    3. easier to design guis
    4. the fact that most ORMs work better with single field PKs (unfortunately)
    5. easier to delete records

    In your case although you can have a composite/surrogate key on person_id and book_id and it will be very useful, you can also have a single id column which CAN be your primary key also, but it does not have to be. You can use the person_id and book_id as PK or just an index, and same for id columns. The id column makes your life easier when deleting stuff or selecting single columns for view purposes. With today's RDBMS's where you normally don't have to worry about table size, it is advisable to include a single column - preferably auto increment identity columns to all your tables just in case it is needed. I believe it won't harm you in any way.

提交回复
热议问题