1.外碼是另外一個表的主碼;
2.插入數據是必須先給所關聯外碼的那個表插入數據;
3.報錯的原因是插入的某個屬性在所關聯外碼表中找不到。
外碼的意義是:保證兩個表之間的數據的一致性,例如:職工表中的部門號,必須在部門表中存在。
create table 部門(
部門號 char(20) primary key not null,
名稱 char(20) constraint UK_dName unique not null ,
經理名 char(20),
地址 varchar(20),
電話號碼 char(20)
)
drop table 部門
create table 職工(
職工號 char(20) primary key,
姓名 char(20) not null,
年齡 smallint check (年齡>=18 and 年齡<=60),
職務 char(20),
工資 int not null check(工資>=800),
部門號 char(20)
FOREIGN KEY (部門號) REFERENCES 部門(部門號)--直接建立外碼
)
drop table 職工
--新增關系表屬性
--新增表的外碼
--方法二:
alter table 職工
add constraint S_worker
foreign key(部門號)
references 部門(部門號)