Two foreign keys instead of primary

2019-01-25 10:13发布

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, a STOCK table with item_id and warehouse_id as foreign keys from ITEMS and WAREHOUSES tables. So same item can be in different warehouses. The view of the table:

item_id   warehouse_id   quantity
10        200            1000
10        201            3000
10        202            10000
11        200            7000
11        202            2000
12        203            5000

Or do i have to create unused primary key field with auto increment or something? The database is oracle.

Thanks!

8条回答
看我几分像从前
2楼-- · 2019-01-25 10:20

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.

查看更多
ら.Afraid
3楼-- · 2019-01-25 10:21

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)
);
查看更多
叼着烟拽天下
4楼-- · 2019-01-25 10:28

If you aren't doing any sort of query that needs it, you don't need a primary key. It makes it a tiny bit harder to delete a record unambiguously, though. You might want to put a unique constraint on item_id,warehouse_id if Oracle allows that.

查看更多
可以哭但决不认输i
5楼-- · 2019-01-25 10:29

yes it is called a compound primary key

查看更多
放荡不羁爱自由
6楼-- · 2019-01-25 10:31
▲ chillily
7楼-- · 2019-01-25 10:31

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.

查看更多
登录 后发表回答