創建主鍵方式
1.一個表的主鍵是唯一標識,不能有重復,不允許為空。
2.一個表的主鍵可以由一個字段或多個字段共同組成。
-- 列級,表級建立主鍵 1.create table constraint_test ( name_id number not null constraint cons_name_id primary key, old number ) 2.create table constraint_test ( name_id number primary key, old number ) drop table constraint_test; 3.create table constraint_test ( name_id number not null, old number , constraint cons_name_id primary key ( name_id ) ); drop table constraint_test; 4.create table constraint_test ( name_id number not null, old number ); alter table constraint_test add constraint cons_name_id primary key ( name_id );
外鍵
drop table course ; drop table students ; create table students (code number , name varchar2(10), country varchar2(30) ); alter table students add constraint pk_st_cod primary key ( code); insert into students values(0001,'zhangsan','shanghai'); insert into students values(0002,'lisi','beijing'); insert into students values(0003,'wangwu','guangzhou'); create table course (id number, code number, name varchar2(10), subject varchar2(30) ); alter table course add constraint pk_co_id primary key ( id); alter table course add constraint fk_co_st foreign key ( code) references students(code); alter table students add foreign key pk_co_id on id; inser into course(id,code,name,subject) values(1,001,'zhangsan','yuwen'); inser into course(id,code,name,subject) values(2,001,'zhangsan','shuxue');
總結:如果要刪除有外鍵的表,必須刪除關聯表數據