MySQL约束

约束

约束(constraint)概述

为什么要约束

为了保证数据完整性

MySQL约束

什么是约束

对表中 字段的(强制)限制

约束的分类

  • 角度一:字段个数

单类约束,多列约束

  • 角度二:约束的作用范围 / 定义位置

列级约束:在字段后声明此约束

[En]

Column-level constraint: declare this constraint after the field

表级约束:在声明表中的所有字段后声明的约束

[En]

Table-level constraints: constraints declared after all fields in the table are declared

  • 约束的作用(功能)

not null (非空约束)

unique (唯一性约束)

primary key (主键约束)

foreign key (外键约束)

check (检查约束)

default (默认值约束)

如何添加约束

CREATE TABLE 添加约束
ALTER TABLE 增加、删除约束

如何查看表中约束

select * from information_schema.table_constraints
where table_name ='表的名字';

NOT NULL (非空约束)

限定某个字段 / 某列的值不能为空

特点

  • 默认所有类型的值都可以是NULL,包括INT,FLOAT等
  • 非空约束只能出现在表对象的列上,只有一列不为空,不能与非空组合(仅列级约束)
    [En]

    non-empty constraints can only appear on the columns of table objects, only a column * is not empty * , and cannot be combined with non-empty (column-level constraints only)*

  • 一个表可以有多个列分别设置为非空
    [En]

    A table can have many columns set to non-empty respectively*

  • 字符串’ ‘不等于NULL;0也不等于NULL

添加非空约束

CREATE TABLE 添加约束

CREATE TABLE emp2(           #建议大写
id int not null,
name varchar(15) not null,
email varchar(25),
salary decimal(10,2)
);
desc emp2;

#正确
insert into emp2(id,name,email,salary)
values(1,'Tom','tom@1126.com',3400);
#错误
insert into emp2(id,name,email,salary)
values(null,'Tom','tom@1126.com',3400);
insert into emp2(id,name,email,salary)
values(1,null,'tom@1126.com',3400);

MySQL约束

ALTER TABLE 增加约束

#增加
alter table emp2
modify email varchar(25) not null;

删除非空约束

#删除
alter table emp2
modify email varchar(25) null;

:若在之前已经让要修改的字段中有null,则要先将null去除

UNIQUE (唯一性约束)

用来限制某个字段 / 某列的值不能重复

特点

  • 同一个表可以有多个约束
  • 唯一约束是一列的值是唯一的,或者多列组合的值是唯一的
    [En]

    the unique constraint is that the value of a column is unique, or the value of a combination of multiple columns is unique*

  • 唯一性约束允许列值为空(可以多次添加null)
  • 创建唯一性约束时,如果不命名唯一约束,则默认为与该列同名(如果有多列,则与第一个列名相同)
    [En]

    when creating a uniqueness constraint, if you do not name the unique constraint, the default is the same name as the column (if there are multiple columns, the same as the first column name)*

添加唯一约束

单列

CREATE TABLE 添加约束

CREATE TABLE emp3(
id int unique,
name varchar(15),
email varchar(25),
salary decimal(10,2),
#表级约束
constraint uk_emp3_email unique (email)
           #约束名的名字
);
desc emp3;

#正确
insert into emp3(id,name,email,salary)
values(1,'Tom','tom@126.com',4500);
insert into emp3(id,name,email,salary)
values(2,'Tom1',null,4700);
insert into emp3(id,name,email,salary)
values(3,'Tom2',null,4600);
#错误
insert into emp3(id,name,email,salary)
values(1,'Tom3','to1@126.com',4500); #id重复

MySQL约束

ALTER TABLE 增加约束

#添加
方式一:
alter table emp3
add constraint uk_emp3_sal unique (salary);#和表级约束差一样
                #约束的名字
方式二:
alter table emp3
modify name varchar(15) unique;#和列级约束一样

多列(复合型唯一性约束)

约束后的字段中的数据, 不能都是一样,只要有一点不同,就可以执行

CREATE TABLE USER(
id int ,
name varchar(15),
·password· varchar(25),
#表级约束
constraint uk_USER_name_pwd unique (name,password)
           #约束名的名字
);
#正确
insert into USER
values (1,'Tom','abc');
insert into USER
values (1,'Tom','abcd');
#错误
insert into USER
values (1,'Tom','abc'); #

删除唯一性约束

  • 在添加唯一约束的列上自动创建唯一索引
    [En]

    unique indexes are automatically created on columns that add unique constraints*

  • 删除唯一约束 只能通过删除唯一索引的方式删除
  • 删除时需要指定唯一索引名,与唯一约束名称相同(参见唯一约束特征)
    [En]

    when deleting, you need to specify a unique index name, which is the same as the unique constraint name (see unique constraint characteristics)*

#删除alter table emp3drop index 索引名;

PRIMARY KEY(主键约束)

用于唯一标识表中的一行记录(区分不同的行)

[En]

Used to uniquely identify a row of records in a table (distinguish between different rows)

特点

  • 主键约束相当于 非空约束+唯一约束,主键约束列不可以重复和出现空值
  • 一个表最多 一个主键约束(可以列级,也可以表级)
  • 如果是多列约束,则这些列不能有空值,组合后的值不能重复。
    [En]

    if it is a multi-column constraint, these columns cannot have null values, and the combined values cannot be repeated.*

  • MySQL的主键名是PRIMARY, 就算自己命名了主键名也没用
  • 创建主键约束时,系统建立对应的主键索引(主键查询,高效)
    [En]

    when creating a primary key constraint, the system establishes the corresponding primary key index (primary key query, efficient)*

  • 不要修改主键字段的值(主键是数据记录的唯一标识),可能会破坏数据的完整性

添加主键约束

单列

CREATE TABLE 添加约束

CREATE TABLE emp4(
id int primary key,#列级约束
name varchar(15),
email varchar(25),
salary decimal(10,2)
);

CREATE TABLE emp5(
id int,
name varchar(15),
email varchar(25),
salary decimal(10,2),
constraint pk_emp5_id primary key (id)#表级约束,但是没有必要起名字
);

#正确
insert into emp4(id,name,email,salary)
values(1,'Tom','tom@1126.com',3400);
#错误
insert into emp4(id,name,email,salary)
values(1,'Tom','tom@1126.com',3400); #id重复
insert into emp4(id,name,email,salary)
values(null,'Tom','tom@1126.com',3400); #出现null值

ALTER TABLE 增加约束

ALTER TABLE emp6
add primary key (id);

多列

CREATE TABLE USER1(
id int ,
name varchar(15),
·password· varchar(25),
primary key (name,password)
);

删除主键约束(实际开发中不会删除)

alter table emp6
drop primary key;

自增列:AUTO_INCREMENT

让某个字段的值自增

特点和要求

  • 一个表只能有一个自增长列
    [En]

    A table can have only one self-growing column*

  • 自增列必须是键列(主键列、唯一键列)
    [En]

    self-incrementing column must be a key column (primary key column, unique key column)*

  • 自增约束的列类型必须为整数
    [En]

    the column type of the self-increasing constraint must be an integer*

  • 如果自增列指定了0和null,会在当前最大值上自增;如果自增列手动指定了具体值,直接赋值具体值

:在实际开发中如果主键作用的字段有auto_increment,则在添加数据是不需要对该字段去赋值

添加自增长列

CREATE TABLE 添加约束

CREATE TABLE emp7(
id int primary key auto_increment ,
name varchar(15)
);

insert into emp7(name)
values('Tom'); #执行一次,id+1不需要赋值

ALTER TABLE 增加约束(一般不会使用)

alter table emp8 #id已经是主键
modify id int auto_increment;

删除自增列

alter table emp8
modify id int;

MySQL8.0新特性——自增量的持久性

若删除一行记录,重启服务器,再执行添加语句,则该自增列的值=刚才删除的行的自增列的数+1

FOREIGN KEY(外键约束)

限制表中字段的引用完整性

[En]

Limit the referential integrity of a field in a table

不可以跨存储引擎

主表和从表 / 父表和子表

  • 主表(父表):被引用表、参与表
    [En]

    Master table (parent table): referenced table, participating table*

  • 来自表(子表):引用他人的表,引用他人的表
    [En]

    from tables (child tables): refer to other people’s tables and refer to other people’s tables*

eg:学生表和课程表是主表,选课表是从表

特点:

  • 备表的外键列必须是主表的主键列或唯一约束列(引用的数字必须唯一)
    [En]

    the foreign key column of the slave table must be the primary key column of the master table or the unique constraint column (the number referenced must be unique)*

  • 创建外键约束时,如果没有名称,默认名称不是列名,而是自动生成外键名称
    [En]

    when creating a foreign key constraint, if there is no name, * the default name is not a column name, but a foreign key name is automatically generated * *

  • 创建外键时,先创建主表,再创建从表
    [En]

    when creating a foreign key, first create a master table, and then create a slave table*

  • 删除时,先删除备表(或外键约束),再删除主表(删除数据也是如此)
    [En]

    when deleting, delete the slave table (or foreign key constraint) first, and then delete the master table (the same is true if the data is deleted)*

  • 在子表中创建外键约束,一张表中也可以建立多个外键约束
    [En]

    create foreign key constraints in a slave table, and multiple foreign key constraints can also be established in a table*

  • 备表的外键列可以与主表的引用列不同,但数据类型必须相同
    [En]

    the foreign key column of the slave table can be different from the reference column of the master table, but * the data type must be the same * *

  • 创建外键约束时,系统默认在列上建立对应的普通索引,但索引名是列名,而不是外键的约束名。
    [En]

    when creating a foreign key constraint, the system establishes a corresponding * general index * on the column by default, but the index name is the column name, not the constraint name of the foreign key.*

  • 删除外键后,必须手动删除对应的索引
    [En]

    after deleting the foreign key, the corresponding index must be deleted manually*

添加外键约束

CREATE TABLE 添加约束

#先创建主表
CREATE TABLE dept1(
dept_id int primary key,#必须给要关联的列添加主键或是唯一约束
dept_name varchar(15)
);
#创建从表
CREATE TABLE emp01(
emp01_id int primary key auto_increment,
emp01_name varchar(15),
department_id int,
#表级约束
constraint fk_emp01_id foreign key(department_id) references dept1(dept_id)
);

#演示外键效果
insert into dept1
values (10,'IT');#先创建主表的数据10号部门

INSERT INTO emp01
values (1001,'Tom',10);
#若是删除或是更改当前主表中的10号部门,是不可行的

ALTER TABLE 增加约束

#主表
CREATE TABLE dept2(
dept_id int primary key,
dept_name varchar(15)
);
#从表
CREATE TABLE emp02(
emp01_id int primary key auto_increment,
emp01_name varchar(15),
department_id int,
);

alter table emp02
add constraint fk_emp02_deot_id foreign key (department_id) references dept2(dept_id);

约束等级

MySQL约束

最好采用ON UPDATE CASADE ON DELETE RESTRICT 的方式,声明位置在约束条件的后面

删除约束

  1. 先查看约束名和删除外键约束
select * from information_schema.table_constraints
where table_name ='表的名字';

alter table 从表名
drop foreign key 约束名;

MySQL约束
  1. 查看索引名,并删除(只能手动)
show index from 表名;

alter table 从表名
drop index 索引名;

MySQL约束

开发场景

外键会让操作受到限制

不建议使用外键和级联。所有外键概念都必须在应用层解决(经典的白色学习)

[En]

Foreign keys and cascading are not recommended. All foreign key concepts must be solved at the application layer (classical white learning)

CHECK (检查约束)

检查一个字段的值是否满足相应的要求,一般是指取值的范围

[En]

Check whether the value of a field meets the corresponding requirements, which generally refers to the range of values

MySQL5.7 不支持CHECK约束

CREATE TABLE emp10(
id int,
name varchar(15),
salary decimal(10,2) check (salary > 2000)
);

insert into emp10
values (1,'Tom',3000);#成功
insert into emp10
values (2,'Tom1',1500);#失败

DEFAULT(默认值约束)

给某个字段 / 某列指定一个默认值,一旦指定以后,在插入数据时,如果此字段没有显示赋值,则赋值为默认值

添加默认值约束

CREATE TABLE 添加约束

CREATE TABLE emp11(
id int,
name varchar(15),
salary decimal(10,2) default 2000
);

insert into emp11
values (1,'Tom',3000);#成功
insert into emp11(id,name)
values (2,'Tom1');#默认添加2000的工资

MySQL约束

ALTER TABLE 增加约束

ALTER TABLE emp12
modify salary varchar(8,2) default 2500;

删除默认值约束

ALTER TABLE emp12
modify salary varchar(8,2);#直接去掉(NOT NULL差不多)

Original: https://www.cnblogs.com/wht-de-bk/p/16006222.html
Author: T,a,o
Title: MySQL约束

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/505564/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • Django后台美化

    Django后台美化 1.Xadmin 1.1 安装 通过如下命令安装xadmin的最新版: pip install https://github.com/sshwsfc/xadm…

    数据库 2023年6月14日
    080
  • MySql 删除数据表

    定义: 删除数据表就是将数据库中已经存在的表从数据库中删除。注意,在删除表的同时,表的定义和表中所有的数据均会被删除。因此,在进行删除操作前,最好对表中的数据做一个备份,以免造成无…

    数据库 2023年6月14日
    071
  • 三分钟入门 InnoDB 存储引擎中的表锁和行锁

    各位对 “锁” 这个概念应该都不是很陌生吧,Java 语言中就提供了两种锁:内置的 synchronized 锁和 Lock 接口,使用锁的目的就是管理对共…

    数据库 2023年6月6日
    079
  • 教师节我用Python做了个学生点名系统送给老师当礼物,这回毕业稳了

    今年教师节前夕,我特意用Python做了个学生点名系统,非常好用,送给各科老师、辅导员当节日礼物,老师们都喜滋滋,说平常逃课就原谅我了,我心想,这次毕业应该不是问题了~ 本文背景 …

    数据库 2023年6月14日
    076
  • 第18章 MySQL8其它新特性

    第18章 MySQL8其它新特性 1. MySQL8新特性概述 MySQL从5.7版本直&a…

    数据库 2023年6月6日
    077
  • 运行的第一个Django

    2022-09-24 创建了一个Django项目后,进行测试,输入指令: python manage.py runserver 出现了如下问题: 我还想着,Django模块通过安装…

    数据库 2023年6月14日
    070
  • day04-1群聊功能

    多用户即时通讯系统04 4.编码实现03 4.5功能实现-群聊功能实现 4.5.1思路分析 群聊的实现思路和私聊的实现非常类似。 不同的是:私聊时,服务端接收到消息后,只需要找出接…

    数据库 2023年6月11日
    071
  • 2010最危险的编程错误(转)

    网络无处不在的今天,安全问题日益严峻,攻击事件层出不穷,应该说,软件系统中代码存在安全漏洞是主要的祸因之一。而这实际上反映了软件开发人员在编程的安全性方面缺乏必要的培训和常识。 由…

    数据库 2023年6月11日
    083
  • Mybatis缓存机制

    MyBatis是常见的 Java数据库访问层框架。在日常工作中,多数情况下是使用 MyBatis的默认缓存配置减轻数据库压力,提高数据库性能,但是 MyBatis缓存机制有一些不足…

    数据库 2023年6月11日
    0116
  • MySQL主从备库过滤参数分析和测试

    测试环境: GTID的主从复制,主库(9900)——》备库(9909),存在测试库表: 9900_db1库:t1、t2、t3、t4、t5表 9900_db2库:t6、t7、t8、t…

    数据库 2023年6月16日
    065
  • 第十七章 AOP编程

    1.AOP概念 AOP(Aspect Oriented Programing) 面向切面编程 = Spring动态代理开发 以切面为基本单位的程序开发,通过切面间的相互协同,相互调…

    数据库 2023年6月14日
    081
  • 实验:非GTID 一主多从变级联架构

    个个原创文章 欢迎讨论https://www.cnblogs.com/konggg/欢迎转载收藏,转载请注明来源,谢谢支持! Original: https://www.cnblo…

    数据库 2023年6月16日
    0102
  • Minio的安装与使用

    Minio的安装与使用 一、Minio介绍 MinIO 是在 Apache License v2.0 下发布的高性能对象存储. 就是说是个存东西的玩意,比较方便配好启动就能访问,也…

    数据库 2023年6月6日
    089
  • 微服务架构设计模式

    内容简介 成功地开发基于微服务架构的应用软件,需要掌握一系列全新的架构思想和实践。在这本书籍中解释了 44 个架构设计模式,这些模式用来解决诸如服务拆分、事务管理、查询和跨服务通信…

    数据库 2023年6月6日
    0136
  • HTML5基础知识

    作者导言: 引用偶像刘德华的一句话 “学到的就要教人,赚到的就要给人”! 以下是关联的web前端基础知识文章,通过这些文章,您既可以系统地学习和了解这些知识…

    数据库 2023年6月14日
    049
  • TortoiseGit的下载以及配置

    TortoiseGit 人称 _小乌龟插件_是一个来源的版本控制客户端,和 git功能类似, 不过相对于git支持界面操作. TortoiseGit下载地址: 点我下载 当前稳定版…

    数据库 2023年6月16日
    076
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球