表操作

2019-04-14 22:08发布

      //创建新表
create table stu(
id number(6),
name varchar2(20) constraint stu_name_nn not null,
sex number(1) ,
age number(3) ,
sdate date,
grade number(2) default 1,
class number(4),
email varchar2(50),
constraint stu_name_email_uni unique(name,email),
constraint fk_stu_class foreign key(class) references class(id),
constraint check_stu_class check(age<30)
);

constraint stu_name_email_uni unique(name,email) name和email字段组合唯一
constraint fk_stu_class foreign key(class) references class(id) class字段引用表class的字段id
constraint check_stu_class check(age<30) 检查age是否小于30
  约束直接写在字段后面叫字段级约束
约束五种
1.非空约束 not null
2.唯一约束 unique ,但是可以插入两个null
组合唯一,使用表级约束
constraint stu_name_email_uni unique(name,email)
3.主键约束
4. 外键约束
表级外键
constraint fk_stu_class foreign key(class) references class(id)
字段级 class number(4)  references class(id),
被参考的class表id字段必须是主键
  create table class(
id number(4) primary key,
name varchar2(20) not null
)
insert into stu(id,name,class,email) values(1,'a',1000,'a');
5.检查性约束
constraint check_stu_class check(age<30)
    //增加字段
alter table stu
add(address varchar2(50))
//修改字段
alter table stu
modify
(address varchar2(150));
//删除字段
alter table stu
drop (address)
//删除约束
alter table stu
drop constraint STU_NAME_EMAIL;
//增加约束
alter table stu
add
constraint STU_NAME_EMAIL unique(name,email);
//删除表
drop table stu;