Two foreign keys instead of primary

后端 未结 8 1602
陌清茗
陌清茗 2020-12-17 21:28

I was wondering, is there any possibility to create a table without a primary key, but with two foreign keys, where the foreign keys pairs are always different? For example,

相关标签:
8条回答
  • 2020-12-17 22:04

    Like this:

    create table stock
    ( item_id      references items(item_id)
    , warehouse_id references warehouses(warehouse_id)
    , quantity     number(12,2) not null
    , constraint stock_pk primary key (item_id, warehouse_id)
    );
    
    0 讨论(0)
  • 2020-12-17 22:05

    yes it is called a compound primary key

    0 讨论(0)
  • 2020-12-17 22:06

    There's nothing wrong with a compound primary key for this but's probably easier in most situations to create a single primary key column anyway. Unless you have particular hardware constraints, the pk col will probably only improve performace and easy of maintainance.

    Don't forget to consider that you may have situations which may not neatly fit your model. For example, you may have stock which you know exists but do not currently know which warehouse it is in, or in transit or not yet allocated or whatever. You either need to create business rules to fit this into your compound primary key or use a primary key column instead.

    0 讨论(0)
  • 2020-12-17 22:09

    Like everyone has said, you can create a primary from 2 columns. You don't have to create an artificial auto increment column.

    Also, bear in mind that foreign keys serve a different purpose than primary keys. So you can't replace a primary key with 2 foreign keys.

    0 讨论(0)
  • 2020-12-17 22:12

    You can create a primary key on two columns: click on both columns in designer view > click on pk

    Or, you could add a unique constraint on 2 columns:

    ALTER TABLE [dbo].[RepresentativeData] 
    add CONSTRAINT [UK_Representative_repRecID_AppID] unique (repRecID,AppId)
    go
    

    I prefer the compound primary key, because it enforces that the value does exist in the other tables.

    0 讨论(0)
  • 2020-12-17 22:13

    You don't have to create a "unused" primary key field, but it often makes life simpler. (As Paul T points out, you'd have to specified both field to delete a row).

    I often name such columns "PK", to make their limited utility obvious.

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