SQL约束
SQL约束:
primary key:主键约束 --- 1、区分记录的唯一性;2、值不能重复也不能为空;3、一张表中只能有一个主键;4、同时将多个字段作为一个主键来使用,多个字段联合起来的值不能重复
例:
create table if not exists stu1 (
id int unsigned primary key,
name varchar(20)
)
create table if not exists stu2 (
id int unsigned,
name varchar(20),
primary key(id)
)
create table if not exists stu2 (
id int unsigned,
name varchar(20),
primary key(id,name)
)
auto_increment:自动递增
create table if not exists stu6 (
id int unsigned primary key auto_increment,
name varchar(20),
)
unique: 唯一约束: 1、保证某个字段值永远不重复;2、允许多个NULL值存在;3、一张表中只能有一个主键,但是可以有多个unique
create table if not exists stu7 (
id int unsigned primary key auto_increment,
name varchar(20) unique,
)
not null:非空约束
create table if not exists stu8 (
id int unsigned primary key auto_increment,
name varchar(20) not null,
)
default:默认值
create table if not exists stu9 (
id int unsigned primary key auto_increment,
name varchar(20) not null,
gender enum('男', '女', '保密') default '保密'
createdAt timestamp default current_timestamp
updateAt timestamp default current_timestamp on update current_timestamp
)
foreign key:外键约束
为什么找不到我的笔记了
约束
主键id并不为空,类型int,是正数
约束类型:
主键约束:primary key 不能为空、不能重复、一张表只能有一个主键,但是可以同时将多个字段作为一个主键来用(联合主键),如primary key(id, name)
外键约束:foreign_key
唯一约束:unique,一般适用于身份证、电话号等场景
自动递增:auto_increment,一般配合主键使用
非空约束:not null
默认值:default