MySQL表的非外键约束
/*
建立一张用来存储学生信息的表
字段包含学号、姓名、性别,年龄、入学日期、班级,email等信息
学号是主键 = 不能为空 +? 唯一
姓名不能为空
性别默认值是男 ,只能取值男、女
年龄:18---50
Email唯一
*/
1,列级约束
创建数据库表
create table student(sno int(6) primary key auto_increment,sname varchar(10) not null ,sex char(1) default '男' check( sex ='男' || sex='女'),age int(3) check (age>=18 and age <=50),enterdate date,classname varchar(10),email varchar(15) unique
);
添加数据
insert into student values(1,'张三','男',34,'1999-12-23','Java001','zhs@qq.com');
insert into student values(null,'张三','男',34,'1999-12-23','Java001','zhs2@qq.com');
insert into student values(default,'李四',null,34,'1999-12-23','Java001','lisi@qq.com');
insert into student (sno,sname,enterdate)values(null ,'王五','2001-12-24');
查询数据
删除数据库表
drop stable student;
2、表级约束
创建数据库表
create table student(
sno int(6) auto_increment,
sname varchar(10) not null ,
sex char(1) default '男',
age int(3),
enterdate date,
classname varchar(10),
email varchar(15),
constraint pk_stu primary key(sno),
constraint ck_stu_sex check(sex ='男' or sex ='女'),
constraint ck_stu_age check(age>=18 and age<=50),
constraint uk_stu_email unique(email)
);
添加数据
insert into student values(1,'zhangsan','男',34,'1999-12-23','Java001','zhs@sxt.cn');
insert into student values(null,'zhangsan','男',34,'1999-12-23','Java001','zhs2@sxt.cn');
查询数据
查看表的结构
desc student;