oracle 如何添加复合主键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18887403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add composite primary keys?
提问by Guru
I have a table with three columns, [Id,QTY,Date
]. out of these three, two columns [id and date], should be set as primary keys, because I need to fetch the record one by one, from this table, into a reference.
我有一个包含三列 [ Id,QTY,Date
]的表格。在这三列中,两列[id和date]应该设置为主键,因为我需要从这张表中一一获取记录,放入一个引用中。
the data to be inserted into this table is
要插入该表的数据是
101,10,NULL
101,20,201220
101,7,201440
102,5,null
102,8,201352
date is in yyyyww
format
日期是yyyyww
格式
How do I define two columns as composite primary keys when they have null
values, duplicates?
当两列有null
值、重复项时,如何将它们定义为复合主键?
alter table abc add constraint pk primary key (ID, DATE);
if I try to alter the table the error appears
如果我尝试更改表格,则会出现错误
Error report:
错误报告:
SQL Error: ORA-01449: column contains NULL values; cannot alter to NOT NULL
01449. 00000 - "column contains NULL values; cannot alter to NOT NULL"
*Cause:
*Action:
采纳答案by DB_learner
The column name of your table is ID and it is still null and non-unique, how is it possible. If it is primary key of other table try adding a surrogate keycolumn for this table and make it primary key.
你的表的列名是 ID 并且它仍然是 null 和非唯一的,这怎么可能。如果它是其他表的主键,请尝试为此表添加代理键列并使其成为主键。
In case of composite primary key, it should have atleast one not null value(For each row) in the combination of columns. And the combination of column must be unique at all case.
在复合主键的情况下,它应该在列组合中至少有一个非空值(对于每一行)。并且列的组合在任何情况下都必须是唯一的。
For further details check, http://docs.oracle.com/cd/B10500_01/server.920/a96524/c22integ.htm
有关更多详细信息,请查看http://docs.oracle.com/cd/B10500_01/server.920/a96524/c22integ.htm
Correction- If composite primary key is made up of 3 columns, then no column (among 3) can hold NULL value. And the combination of those 3 columns must be unique. E.g. (1,2,2) (1,2,1) (2,2,1) (1,2,2) - not valid
更正- 如果复合主键由 3 列组成,则没有列(3 列中)可以包含 NULL 值。并且这 3 列的组合必须是唯一的。例如 (1,2,2) (1,2,1) (2,2,1) (1,2,2) - 无效
回答by DevYudh
Using table level constraint, you can use this query
使用表级约束,您可以使用此查询
alter table your_table add constraint pkc_Name primary key (column1, column2)
but first you need to declare the columns NOT NULL
. All parts of a primary key need to be NOT NULL
.
但首先你需要声明列NOT NULL
。主键的所有部分都必须是NOT NULL
.