需要引用另一个表,但不能与列相同

时间:2016-04-22 13:46:47

标签: sql oracle constraints

所以我有一个名为Timesheet_approved的coloumn的表funtom_timesheet,我需要引用表funtom_employee(emp ID), 列timesheet_approved也不能与列timesheet_emp的值相同,这是我到目前为止的代码......

create table Funtom_timesheet 
(
timesheet_ID          number(3) constraint timesheet_pk primary key,
timesheet_Emp         number(3) constraint timesheet_Emp not null constraint timesheet_Emp references funtom_employee,
timesheet_Wc          date      constraint timesheet_Wc not null,  
timesheet_OT          number(2) default 0,
timesheet_Approved    number(3)  constraint timesheet_approved references funtom_employee constraint timesheet_approved unique(timesheet_Approved,timesheet_Emp) 
)
;

新代码仍有错误......

create table Funtom_timesheet 
(
    timesheet_ID          number(3) constraint timesheet_pk primary key,
    timesheet_Emp         number(3) constraint timesheet_Emp not null references funtom_employee(emp_ID),
    timesheet_Wc          date      constraint timesheet_Wc not null,  
    timesheet_hours   number(2),
    timesheet_OT          number(2) default 0,
    timesheet_Approved    number(3),
    constraint timesheet_approved_uc unique(timesheet_Approved,timesheet_Emp),
    constraint timesheet_approved references funtom_employee(emp_ID)

);

1 个答案:

答案 0 :(得分:0)

你仍然犯了一些相同的错误,并混合了内联和外线约束的语法。您发布的代码将获得ORA-00907:缺少右括号,因为最后一个约束格式错误:

constraint timesheet_approved references funtom_employee(emp_ID)

应该在此表中指定它适用的约束类型和列名:

constraint timesheet_approved foreign key (timesheet_Approved)
  references funtom_employee(emp_ID)

你对独特约束的尝试也是错误的;检查timesheet_approvedtimesheet_em的组合只能出现在表格的一行中,不是,即同一行中的两列值不同。为此,您需要一个检查约束:

create table funtom_timesheet (
  timesheet_id number(3),
  timesheet_emp number(3) not null,
  timesheet_wc date not null,
  timesheet_hours number(2),
  timesheet_ot number(2) default 0,
  timesheet_approved number(3),
  constraint timesheet_pk primary key (timesheet_id),
  constraint timesheet_fk1 foreign key (timesheet_emp)
    references funtom_employee(emp_id),
  constraint timesheet_fk2 foreign key (timesheet_approved)
    references funtom_employee(emp_id),
  constraint timesheet_check check (timesheet_approved != timesheet_emp)
);

最后一行检查timesheet_approvedtimesheet_emp的号码不同,即有人未批准自己的时间表。这两个字段对有效员工记录都有FK约束;检查约束确保它们不同。