使用多个主键列创建数据库并引用外键时出错

时间:2014-03-30 16:21:15

标签: sql oracle database

我在创建数据库时遇到了问题。每个表都有一个主键,也使用了许多外键。我遇到的问题是我不断收到错误

SQL Error: ORA-02270: no matching unique or primary key for this column-list
02270. 00000 -  "no matching unique or primary key for this column-list"
*Cause:    A REFERENCES clause in a CREATE/ALTER TABLE statement
           gives a column-list for which there is no matching unique or primary
           key constraint in the referenced table.
*Action:   Find the correct column names using the ALL_CONS_COLUMNS
           catalog view

我不知道造成这种情况的原因是什么,并将PROJECT_RECORDS表标记为问题。我在PROJECT_TABLES表中使用了相同的方法。

SQL / Oracle的

CREATE TABLE PROJECT_DB
(DB_ID number (3) NOT NULL primary key,
DB_NAME varchar2 (25) NOT NULL,
DB_DESCRIPTION varchar2 (75) NOT NULL,
DB_DATE date NOT NULL);

CREATE TABLE PROJECT_DATATYPE
(DATATYPE_NAME varchar2 (20) NOT NULL PRIMARY KEY,
DATATYPE_DATATYPE varchar2(50) NOT NULL);

CREATE TABLE PROJECT_TABLES (
PROJECT_ID number(3) not null references PROJECT_DB(DB_ID) on delete cascade,
PROJECT_FIELDNAME varchar2(25) not null,
PROJECT_DATATYPE varchar2(50) not null references PROJECT_DATATYPE(DATATYPE_NAME),
PROJECT_LENGTH number(3),
PROJECT_REQUIRED varchar2(8),
PROJECT_LISTCOLUMNID number (3) not null,
primary key(PROJECT_ID, PROJECT_LISTCOLUMNID));


CREATE TABLE PROJECT_RECORDS (
RECORDS_ROWID number(3) not null,
RECORDS_LISTCOLUMNID number (3) not null references PROJECT_TABLES(PROJECT_LISTCOLUMNID)on delete cascade,
RECORDS_LISTID number (3) not null,
RECORDS_RECORDVALUE varchar2 (25),
primary key(RECORDS_ROWID, RECORDS_LISTCOLUMNID));

commit;

向PROJECT_TABLES表添加多个主键的原因是listcolumnid不是唯一的。

2 个答案:

答案 0 :(得分:0)

问题在于你的语法。你不这样做:

, fieldname datatype references (something)

你这样做:

, primary key(somefield)
, foreign key (somefield) references sometable(somefield)

答案 1 :(得分:0)

如果listcolumnid不唯一,则不能对其设置外键约束。一个外键总是反映出一个父行。因此,您可能应该在外键中使用这两列(假设实际上存在1:n关系):

CREATE TABLE PROJECT_RECORDS (
RECORDS_ROWID number(3) not null,
RECORDS_ID number(3) not null,
RECORDS_LISTCOLUMNID number (3) not null,
RECORDS_LISTID number (3) not null,
RECORDS_RECORDVALUE varchar2 (25),
primary key(RECORDS_ROWID, RECORDS_LISTCOLUMNID),
foreign key fk_project_projectrecords (RECORDS_ID, RECORDS_LISTCOLUMNID) references PROJECT_TABLES(PROJECT_ID, PROJECT_LISTCOLUMNID)on delete cascade,
);

(示例使用您的前缀命名约定,我会将RECORDS_ID更改为PROJECT_ID,同样适用于RECORDS_LISTCOLUMNID