【问题标题】:SQL Creating Table DependenciesSQL 创建表依赖
【发布时间】:2014-12-01 12:50:28
【问题描述】:

我一直忙于创建表格。

这是我被困在如何使代码在loan_type 中工作以编写办公室工作人员或非办公室工作人员的代码

create table loaner 
(
   loan_id number(5) primary key,
   loan_type VARCHAR2 (16),
   loan_start_date date,
   loan_end_date date,
)

create table office_worker 
(
   worker_id number(5) primary_key,
   loan_id number(5) references loaner(loan_id),
   worker_name varchar2(50)
)

create table nonoffice_worker 
(
   nonworker_id number(5) primary_key,
   loan_id number(5) references loaner(loan_id),
   nonworker_name varchar2(50)
);

commit;

【问题讨论】:

  • 您遇到错误了吗?
  • 将所有工作人员都放在一张表中并只有一个名为is_office的列会不会更好
  • 不,没有出错,上班族和非上班族的贷款类型有不同的贷款类型,所以我需要的是如何输入检查声明贷款人类型是上班族还是非上班族工人
  • @Matt 抱歉忘记给你们加标签
  • 他们只是贷款类型工人之间的区别吗?

标签: sql oracle create-table


【解决方案1】:

您无法创建约束来检查现有表结构。一个常见的方法是这样的:

create table loaner (
loan_id number(5) primary key,
loan_type VARCHAR2 (16),
loan_start_date date,
loan_end_date date,
constraint loaner_uk unique (loan_id, loan_type)
);

create table office_worker (
worker_id number(5) primary_key,
loan_id number(5),
loan_type VARCHAR2 (16),
worker_name varchar2(50),
constraint office_worker_loaner_fk foreeign key (loan_id, loan_type) references loaner (loan_id, loan_type),
constraint office_worker_loan_type_chk check (loan_type = 'OFFICE')
);

create table nonoffice_worker (
nonworker_id number(5) primary_key,
loan_id number(5),
loan_type VARCHAR2 (16),
nonworker_name varchar2(50),
constraint nonoffice_worker_loaner_fk foreeign key (loan_id, loan_type) references loaner (loan_id, loan_type),
constraint nonoffice_worker_loan_type_chk check (loan_type = 'NONOFFICE')
);

即:

  1. 在第一个表的 (load_id, loan_type) 中创建一个冗余的 UNIQUE 约束。
  2. 将loan_type 添加到子类型表中,并将外键基于(loan_id,loan_type)。
  3. 为每个子类型表添加检查约束以确保使用正确的loan_type。

【讨论】:

  • 这似乎太复杂了,感谢帮助会解决它
  • 这是一个有效的解决方案。我还添加了检查约束选项,以防他的表在列 loan_type 上有正确的值
【解决方案2】:

你也可以在你的表中添加一个检查约束,但是你必须检查该列 loan_type 是否只包含所需的值(office workernon office worker),否则这将不起作用:

alter table loaner add (CONSTRAINT chk_loan_type CHECK 
(loan_type='office worker' or loan_type='non office worker'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 2010-09-10
    • 2015-08-09
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多