建立主鍵與外來鍵的命令

2021-05-25 02:08:11 字數 1416 閱讀 8339

建立表時,就建立相應的主鍵和外來鍵:
create table t1

(id int primary key,

name varchar(20)

);create table t2

(remark varchar(50),

p_id int references t1(id) /*表示列p_id外來鍵關聯於表t1的列id*/

);需要注意的問題:

1、t1的id必須為key

2、關聯的2個列的資料型別必須一致且必須長度完全一樣。

建立完錶後,再建立相應的外來鍵:
-- 建立測試主表. id 是主鍵.

create table test_main (

id int,

value varchar(10),

primary key(id)

);-- 建立測試子表.

create table test_sub (

id int,

main_id int,

value varchar(10),

primary key(id)

);缺省外鍵約束方式

alter table test_sub add constraint main_id_cons foreign key (main_id) references test_main;

delete cascade 方式

-- 建立外來鍵(使用 on delete cascade 選項,刪除主表的時候,同時刪除子表)

alter table test_sub

add constraint main_id_cons

foreign key (main_id) references test_main on delete cascade;

update cascade方式

-- 建立外來鍵(使用 on update cascade 選項,更新主表的主鍵時候,同時更新子表外來鍵)

alter table test_sub

add constraint main_id_cons

foreign key (main_id) references test_main on update cascade;

set null方式

-- 建立外來鍵(使用 on delete set null 選項,刪除主表的時候,同時將子表的 main_id 設定為 null)

alter table test_sub

add constraint main_id_cons

foreign key (main_id) references test_main on delete set null;

主鍵與外來鍵

一 什麼是主鍵 外來鍵 關係型資料庫中的一條記錄中有若干個屬性,若其中 某乙個屬性組 注意是組 能唯一標識一條記錄 該屬性組就可以成為乙個主鍵 比如 學生表 學號,姓名,性別,班級 其中每個學生的 學號是唯一的,學號就是乙個主鍵 課程表 課程編號 課程名,學分 其中課程編號 是唯一的,課程編號 就是...

建立表主鍵,外來鍵

使用者表 create table gb bbs user id bigint primary key identity 1,1 bbs使用者 memberid bigint foreign key memberid references t member id staus int default ...

建立主鍵 建立外來鍵 建立約束

建立主鍵 三種方法 建立學生表 第一種 create table student sno char 5 primary key,學號 可以直接指定主鍵 sname char 20 not null,姓名 s char 3 not null,性別 sage integer not null,年齡 sd...