MySQL约束

数据库有六大约束,分别为

  • NOT NULL  非空约束,用于保证这个字段不能为空
  • DEFAULT  默认约束,用于保证该字段有默认值
  • PRIMARY KEY 主键约束,用于保证该字段可以唯一表示该行记录,唯一且非空
  • UNIQUE   唯一约束,用于保证该字段的唯一性,可以为空
  • CHECK   检查约束(MySQL不支持该约束)
  • FOREIGN KEY 外键约束,用于限制两个表的关系,用于保证该字段必须来自于主表关联列的值(在从表中添加外键约束,用于引用主表中某列的值)

示例:

create table class( 
  id int primary key, #主键约束
  name varchar(20) not null #非空约束
);

create table student(
	id int,
  name varchar(20) not null,
  classid int,
  sex int not null,
  brith date,
  constraint pk primary key(id), #主键约束
  constraint fk_student_class foreign key(classid) references class(id) #外键
);