重构sql

时间:2014-05-19 08:43:10

标签: sql

我尝试实现一个将用作应用操作的表。客户申请贷款,员工将批准贷款。相应的sql是:

create table approve(
   employee_ID char(8),
   customer_ID char(8), 
   loanID char(8) primary key,
   foreign key(employee_ID) references employee(ID),
   foreign key(customer_ID) references customer(ID) 
)

然而问题是当我尝试插入一个元素时,它要求我输入loanID。但是,应显示贷款ID,员工应根据此loanID确定。这不符合逻辑吗?如果我能修改代码是合乎逻辑的吗?

4 个答案:

答案 0 :(得分:0)

如果loanID来自另一个表格,您也应该将其作为外键处理,就像使用employeecustomer一样:

create table approve(
   employee_ID char(8),
   customer_ID char(8), 
   loan_ID char(8),
   foreign key(loan_ID) references loan(ID),
   foreign key(employee_ID) references employee(ID),
   foreign key(customer_ID) references customer(ID) 
)

如果您想阻止同一笔贷款在表approve中有多个条目,请创建一个索引:

create unique index approve_loan_ID on approve (loan_ID)

答案 1 :(得分:0)

如果它是一对一的关系,那么结构就可以了。

贷款和批准可以共享主键

创建一个批准职位需要一个贷款岗位。贷款只能被批准一次吗?

您需要做的就是将批准的主键设置为贷款的外键。

foreign key(loan_ID) references loan(ID)

答案 2 :(得分:0)

更改您的表格结构,以便您只有贷款,客户和员工表。

添加关系

贷款1 - *客户

“客户可以获得多笔贷款”

贷款0..1 - *员工

“贷款只能获得员工的1份批准”

为贷款添加批准的位标记以将其标记为已批准,或将标记的枚举标记为“已应用”/“已批准”/“已拒绝”/“无论何种”。

答案 3 :(得分:0)

如果贷款只能使用一次,则没有理由换新表。

alter table loan add granter_employee_ID char(8);

alter table loan add grantee_customer_ID char(8);

alter table loan add constraint fk_granter_employee_id 
  foreign key (granter_employee_id) references employee(id);

alter table loan add constraint fk_grantee_customer_id
  foreign key (grantee_customer_id) references customer(id);

我认为即使客户申请贷款也会输入?那么你就会让顾客无法入罪。

alter table loan add grantee_customer_id char(8) not null;

(而且,您可以对列进行不同的命名,因为在输入时贷款不会被授予。)