05-MySQL的完整性约束

1.整体说明
(1)讨论重点内容
    not null 与default
    unique:表中该值唯一,不能有重复值
    primary
    auto_increment
    foreign key
(2)约束条件与数据类型的宽度一致,都是可选参数
(3)作用:用于保证数据的完整性和一致性。
(4)主要分为如下:

    PRIMARY KEY (PK)    #标识该字段为该表的主键,可以唯一的标识记录
    FOREIGN KEY (FK)    #标识该字段为该表的外键
    NOT NULL    #标识该字段不能为空
    UNIQUE KEY (UK)    #标识该字段的值是唯一的
    AUTO_INCREMENT    #标识该字段的值自动增长(整数类型,而且为主键)
    DEFAULT    #为该字段设置默认值

    UNSIGNED #无符号
    ZEROFILL #使用0填充
(5)其他说明如下:
    #1. 是否允许为空,默认NULL,可设置NOT NULL,字段不允许为空,必须赋值
    #2. 字段是否有默认值,缺省的默认值是NULL,如果插入记录时不给字段赋值,此字段使用默认值
    sex enum('male','female') not null default 'male'

    #必须为正值(无符号) 不允许为空 默认是20
    age int unsigned NOT NULL default 20
    # 3. 是否是key
    主键 primary key
    外键 foreign key
    索引 (index,unique...)

2.not null 与default
(1)默认值可以为空。
(2)设置not null时,插入值时不能为空。
(3)设置id字段有默认值后,则无论id字段是null还是not null,都可以插入空,插入空值时默认填入default指定的默认值。

3.unique:唯一
(1)包括单列唯一、多列唯一以及联合唯一。
    create table user4(
        id int unique,
        name char(20)
    );

    create table user4(
        id int,
        name char(20),
        unique(id)
    );
(2)单列唯一
    create table user4(
        id int unique,
        name char(20)
    );
(3)多列唯一
     多列都不相同才可以插入,只要有一列相同都不能插入
    create table user5(
        id int unique,
        name char(20),
        ip char(30)unique
    );

(4)联合唯一
    只要有一列不同 都可以插入。
    create table user6(
        id int,
        name char(20),
        ip char(30),
        unique(id,ip)
    );

4.primary key
在MySQL的一个表中只有唯一的一个主键,不能有多列主键,但可以有复合主键

一个表中可以:

单列做主键
多列做主键(复合主键)

5.auto_increment
(1)不指定ID,则自动增长
(2)指定ID则按照指定的ID增长
(3)对于自增的字段,在用delete删除后,再插入值,该字段仍按照删除前的位置继续增长

6.foreign key

create table emp(
    id int primary key,
    name varchar(20) not null,
    age int not null,
    dep_id int,
    constraint fk_dep foreign key(dep_id) references dep(id)
    on delete cascade #同步删除
    on update cascade #同步更新
);


原文地址:https://www.cnblogs.com/mayugang/p/10222821.html