2016-11-21 100 views
1

我是SQL新手,我有一个问题。我想做一个递归关系(一个与自身相关的表),但是当我尝试执行我的代码时出现错误。它工作正常,没有Coordinator_Office_ID外键。递归关系SQL错误

的错误是:

的外键引用表列数不等于 在引用表中的列数。

Create table Logistican (
    Office_ID Number(10) Constraint nb_office Not NULL, 
    Worker_ID Number(15) Constraint lg_worker not null, 
    Name_logistican Varchar(20), 
    Room Varchar(10) constraint log_room UNIQUE, 
    Coordinator_Office_ID Integer, 
    Primary key (Office_ID, Worker_ID), 
    Constraint work_id Foreign key (Worker_ID) References worker(worker_ID) on  delete cascade, 
    Constraint lg_cord_id Foreign key (Coordinator_Office_ID) References  Logistican(Office_ID) 
); 
+0

为什么要使用不同类型'Coordinator_Office_ID'和'Office_ID'? –

+0

我看到我们的教授这样写了,但我不确定它是否正确 – specbk

回答

2

添加约束与alter table

Create table Logistican (
    Office_ID Number(10) Constraint nb_office Not NULL, 
    Worker_ID Number(15) Constraint lg_worker not null, 
    Name_logistican Varchar(20), 
    Room Varchar(10) constraint log_room UNIQUE, 
    Coordinator_Office_ID Integer, 
    Primary key (Office_ID, Worker_ID), 
    Constraint work_id Foreign key (Worker_ID) References worker(worker_ID) on delete cascade 
); 

alter table Logistican 
    add Constraint lg_cord_id 
     Foreign key (Coordinator_Office_ID, Worker_Id) References  Logistican(Office_ID, Worker_Id); 

的关系需要主键的所有元素是有效的。我不确定它是否需要在Oracle中成为一个单独的声明。

+0

我已经尝试过了,但它仍然无效。 – specbk

+0

谢谢,它的工作! – specbk

2

是的,那是因为你已经定义复合主键像Primary key (Office_ID, Worker_ID),因此您的FK应该包括他们否则它会导致PFD(部分函数依赖)