递归关系SQL错误

时间:2016-11-21 12:17:45

标签: sql database oracle reference recursive-query

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

错误是:

  

外键引用列表中的列数不相等   到引用列表中的列数。

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)
);

2 个答案:

答案 0 :(得分: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中单独声明。

答案 1 :(得分:2)

是的,这是因为你定义了复合主键,如entity_emails_to,因此你的FK应该包括其他两个,否则它将导致PFD(部分功能依赖)