问题1:学号重复了,数据还可以插入成功
使用主键约束:学号是唯一标识一条数据的,所以必须唯一且不能为空
---(1)、在确定为主键的字段后添加 primary key关键字
---(2)、在创建表的后面使用:constraints pk_表名_字段名 primary key(字段名)
--(3)、在创建表后使用 alter table 表名 add constraints pk_表名_字段名 primary key(字段名);
--删除主键:alter table 表名 drop constraints pk_表名_字段名
问题2:姓名可以为空。
使用非空约束
---(1)、创建表的时候在字段后面添加not null
---(2)、在创建表字段后使用 constraints ck_表名_字段名 check(字段名 is not null) 了解
--(3)、在创建表后使用alter table 表名 modify 字段名 类型 not null;
---(4)、修改字段可以存储空值:alter table 表名 modify 字段名 类型 null;
问题3:性别不但可以为空,还可以为其他不知道的字符
使用检查约束
---(1)、创建表的时候在字段后使用 default 值 check(条件),
---------但是会允许空值的出现,并且默认值只有在字段不声明的情况下生效
---(2)、在创建表所有字段后使用:constraints ck_表名_字段名 check(条件)
---(3)、在创建表后使用:alter table 表名 add constraints ck_表名_字段名 check(条件)
问题4:年龄可以超过200
--使用检查约束条件
问题5:qq号一致
使用唯一约束
--(1)、在字段后直接使用unique关键字
--(2)、在所有字段后使用:constraints uk_表名_字段名 unique(字段名)
--(3)、 alter table 表名 add constraints uk_表名_字段名 unique(字段名)
--删除唯一约束:alter table 表名 drop constraints uk_表名_字段名
1、主键约束
三种方式主键约束方式
create table student(
sno number(10) primary key,
sname varchar2(100),
sage number(3),
ssex char(4),
sbirth date,
sqq varchar2(30)
);
create table student(
sno number(10),
sname varchar2(100),
sage number(3),
ssex char(4),
sbirth date,
sqq varchar2(30),
constraint pk_student_sno primary key(sno) ---添加主键约束
);
create table student(
sno number(10),
sname varchar2(100),
sage number(3),
ssex char(4),
sbirth date,
sqq varchar2(30)
);
alter table student add constraint pk_student_sno primary key(sno);
alter table student drop constraint pk_student_sno;
select * from student for update;
drop table student;
非空约束
三种方式
create table student(
sno number(10) primary key,
sname varchar2(100) not null,
sage number(3),
ssex char(4),
sbirth date,
sqq varchar2(30)
);
create table student(
sno number(10) primary key,
sname varchar2(100),
sage number(3),
ssex char(4),
sbirth date,
sqq varchar2(30),
constraints ck_student_sname check(sname is not null)
);
create table student(
sno number(10) primary key,
sname varchar2(100),
sage number(3),
ssex char(4),
sbirth date,
sqq varchar2(30)
);
alter table student add constraint ch_student_sname check(sname is not null);
alter table student drop constraint ch_student_sname
检查约束
create table student(
sno number(10) primary key,
sname varchar2(100) not null,
sage number(3) check(sage<150 and sage>0),
ssex char(4) check(ssex =‘男‘ or ssex = ‘女‘),
sbirth date,
sqq varchar2(30)
);
create table student(
sno number(10) primary key,
sname varchar2(100) not null,
sage number(3),
ssex char(4) check(ssex =‘男‘ or ssex = ‘女‘),
sbirth date,
sqq varchar2(30),
constraint ch_student_sage check(sage<150 and sage>0)
);
create table student(
sno number(10) primary key,
sname varchar2(100) not null,
sage number(3),
ssex char(4) check(ssex =‘男‘ or ssex = ‘女‘),
sbirth date,
sqq varchar2(30)
);
alter table student add constraint ch_student_sage check(sage<150 and sage>0);
alter table student drop constraint ch_student_sage;