数据库
首页 > 数据库> > Mysql完整性约束详解(字段唯一,非空,主键primary key,外键foreign key,自增长auto_increment)

Mysql完整性约束详解(字段唯一,非空,主键primary key,外键foreign key,自增长auto_increment)

作者:互联网

引入

1.什么是完整性约束, 为什么使用

为了规范数据格式, 在用户进行插入、修改、删除等操作时,DBMS(数据库管理系统(Data Base Management System))自动按照约束条件对数据进行监测, 使不符合规范的数据不能进入数据库, 以确保数据的完整性和唯一性

2.约束分类

表完整性约束条件与字段数据类型的宽度一样, 都是可选参数,分为以下几种:

完整性约束关键字含义
NULL标识字段值可以为空
NOT NULL约束字段值不为空
DEAFAULT设置字段值为默认值
UNIQUE KEY(UK)约束字段的值唯一
PRIMARY KEY(PK)设置字段为表的主键
FOREIGN KEY(FK)设置字段为表的外键
AUTO_INCREAMENT约束字段的值为自动递增
UNSIGNED无符号
AEROFILL使用 0 填充

一.null (空)

create table t04(id int); 
insert t04 value();      # values() 也可以 value()
insert t04 value(null);  # 并且 into 可以省略
insert t04 value(1);

image-20210131220611187

二.not null (非空)

create table t05(name char(16) not null);
insert t05 value();
insert t05 value(null);
insert t05 value("shawn");

image-20210131221836514

三.default (默认)

create table t06(name char not null default "shawn");
insert t06 value();
insert t06 value(null);

create table t07(name char not null dafault null);  # 直接报错

image-20210131223045250

四.unique (唯一)

1.单列唯一

create table t07(id int unique,name char(16));
insert t07 value(1,"shawn"),(2,"song");
insert t07 value(1,"xing");  # 报错提示重复

image-20210131231603029

2.联合唯一

create table t08(id int,ip varchar(16),port int,unique(ip,port));  # ip + port 联合单个可以重复, 联合不能相同
insert t08 value(1,"127.0.0.1",8090);
insert t08 value(2,"127.0.0.1",8091);
insert t08 value(3,"127.0.0.1",8090);  # 联合与id为1的相同, 报错

image-20210131234448702

3.not null + unique

五.primary key (主键)

主键约束(primary key)

1.什么是主键约束

2.主键的作用

3.未设置主键如何处理表

ps : InnoDB引擎表是基于B+树的索引组织表(IOT)(自行百度)

4.表的两种主键方式

5.验证演示

create table t09(id int primary key);  # 设置主键
insert t09 value(1),(2);
insert t09 value(null);  # 插入 null 报错
insert t09 value(1);     # 插入id 1 报错
insert t09 value(2);     # 插入id 2 也报错

image-20210201093136789

create table t10(
	id int not null unique,  # 设置 id 字段不为空,且唯一
	name char(16) not null,
	age int,
	sex char(3) not null
);
desc t10;  # 查看表结构

image-20210201093710163

create table t11(
    id int primary key,
    name varchar(16)
);
desc t11;

image-20210201094104260

create table t12(
    ip varchar(16),
    port int,
    primary key(ip,port)  # 设置 IP + port 联合主键
);
insert t12 value("127.0.0.1",8090);
insert t12 value("127.0.0.1",8091);  # 单个字段可以相同
insert t12 value("127.0.0.1",8090);  # 连个字段不能相同, 报错

image-20210201094548983

6.主键总结

六.auto_increment (自增长)

1.自增长说明

2.使用场景

3.自增长演示

create table t13(
    id int primary key auto_increment,
    name varchar(16)
);
insert t13(name) value("shawn"),("xing");

image-20210201102712102

insert t13 value(7,"xing"),(9,"hai");

image-20210201102923392

insert t13(name) value("hello");  # 再次不指定 id 

image-20210201103115923

4.删除表记录和清空表的区别

标签:insert,null,value,主键,key,foreign,id
来源: https://blog.csdn.net/songhaixing2/article/details/113528092