oracle知识整理

来源:互联网 发布:反淘宝联盟yy是多少 编辑:程序博客网 时间:2024/06/06 07:15

额滴数据库太薄弱了,整理一下知识点吧:

外键(foreign key)约束:

在建表之后,为表增加外键约束可以像下面这样操作:

为表增加外键约束:

1、alert  table student 

2、add constraint stu_fk foreign key (classid)

3、references class(classid)

为student表增加外键(我们称student为字表)。

其中,第二行代码表示为student表的classid字段增加外键约束,外键约束的别名叫stu_fk。

第三行代码表示该外键约束指向class表中的classid列。

注意:外键列(第一个classid)和被引用列(第二个classid)的列名可以不同,但是数据类型要相同;另外,在创建外键约束之前,父表必须已经存在,并且父表的引用列也就是父表的主键列必须被定义为unique或者primary key约束。


在建表时,为表增加外键约束可以像下面这样操作:

create table student(

stu_id number(8) not null primary key; //表的主键

stu_code varchar2(10) ,

classid number(4) references class(classid) // /表的外键

);


删除外键约束:

alert  table student  drop constraint  stu_fk f(外键约束)


check约束:

在建表时创建约束:

为列指定check约束,如下:

create table student(

stu_id number(8) not null primary key; //表的主键

stu_code varchar2(10)  unique,

stuage number(3) constraint age_ck check(stuage > 0)

classid number(4) references class(classid) // /表的外键

);


在建表后创建约束:

alert  table  student add  constraint stuage_ck check(stuage > 0);


删除约束:

alert  tablestudent  drop constraint stuage_ck;


unique约束:

如果为列定义unique约束,那么该列中不能包含重复的值,可以在同一个列上建立unique和not null

在建表时创建unique:

create table student (

stuid number(10) not null  primary key,

stucode number(20) constraint stu_uk unique,

stuage number(3)  constraint  stuag_ck check(stuage > 0)

);

如果为一个列建立unique约束,而没有not null 约束,则该列的数据可以包含多个null值,多个null值不算重复值。


在建表后创建unique:

alert  table  student  add unique(stuname);


删除unique约束:

alert  table student  drop  unique(stuname)或

alert  table student  drop  constraintstu_uk(约束名)