zoukankan      html  css  js  c++  java
  • mysql 完整性约束

    介绍

    约束条件与数据类型的宽度一样,都是可选参数

    作用:用于保证数据的完整性和一致性
    主要分为:

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

    说明:

    1. 是否允许为空,默认NULL,可设置NOT NULL,字段不允许为空,必须赋值
    2. 字段是否有默认值,缺省的默认值是NULL,如果插入记录时不给字段赋值,此字段使用默认值
    sex enum('male','female') not null default 'male'
    age int unsigned NOT NULL default 20 必须为正值(无符号) 不允许为空 默认是20
    3. 是否是key
    主键 primary key
    外键 foreign key
    索引 (index,unique...)
    

     

    not null与default

    是否可空,null表示空,非字符串
    not null - 不可空
    null - 可空
    
    
    默认值,创建列时可以指定默认值,当插入数据时如果未主动设置,则自动添加默认值
    create table tb1(
    nid int not null defalut 2,
    num int not null
    )
    

     

    验证:

    id字段默认可以插入空
    use db1;
    
    create table t3(id int); #id字段默认可以插入空
    desc t3;
    

      

    insert into t3 values();
    commit;
    
    select * from t3;
    

     

     

    #设置字段id不为空
    create table t5(id int not null); #设置字段id不为空
    desc t5;
    

      

    insert into t5 values(); #不能插入空
    ERROR 1364 (HY000): Field 'id' doesn't have a default value
    

      

    设置id字段有默认值
    #设置id字段有默认值后,则无论id字段是null还是not null,都可以插入空,插入空默认填入default指定的默认值
    create table t7(id int default 1);
    alter table t7 modify id int not null default 1;
    desc t7;
    

     

    unique

    单列唯一

    #============设置唯一约束 UNIQUE===============
    #方法一:
    create table dep1(
    id int,
    name varchar(20) unique
    );
    
    
    #方法二:
    create table dep2(
    id int,
    name varchar(20),
    constraint uk_name unique(name)
    );
    

      

    insert into dep1 values(1,'IT','技术');
    Query OK, 1 row affected (0.00 sec)
    insert into dep1 values(1,'IT','技术');
    ERROR 1062 (23000): Duplicate entry 'IT' for key 'name'

    not null+ unique

    变为primary key

     多列唯一

    create table server(
    id int primary key auto_increment,
    host char(20),
    port int,
    constraint uni_hostport unique (host, port)
    );
    
    desc server;
    
    insert into server(host,port) values('192.168.20.11',8080);
    insert into server(host,port) values('192.168.20.11',8081); #ip和端口合起来唯一
    commit;
    
    select * from server;
    
    insert into server(host,port) values('192.168.20.11',8080);
    Error Code: 1062. Duplicate entry '192.168.20.11-8080' for key 'uni_hostport'
    

      

    primary key

    primary key字段的值不为空且唯一

    一个表中可以:

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

    但一个表内只能有一个主键primary key

    单列做主键:

    ============单列做主键===============
    #方法一:not null+unique
    create table department1(
    id int not null unique, #主键
    name varchar(20) not null unique,
    comment varchar(100)
    );
    
    mysql> desc department1;
    +---------+--------------+------+-----+---------+-------+
    | Field   | Type         | Null | Key | Default | Extra |
    +---------+--------------+------+-----+---------+-------+
    | id      | int(11)      | NO   | PRI | NULL    |       |
    | name    | varchar(20)  | NO   | UNI | NULL    |       |
    | comment | varchar(100) | YES  |     | NULL    |       |
    +---------+--------------+------+-----+---------+-------+
    rows in set (0.01 sec)
    
    #方法二:在某一个字段后用primary key
    create table department2(
    id int primary key, #主键
    name varchar(20),
    comment varchar(100)
    );
    
    mysql> desc department2;
    +---------+--------------+------+-----+---------+-------+
    | Field   | Type         | Null | Key | Default | Extra |
    +---------+--------------+------+-----+---------+-------+
    | id      | int(11)      | NO   | PRI | NULL    |       |
    | name    | varchar(20)  | YES  |     | NULL    |       |
    | comment | varchar(100) | YES  |     | NULL    |       |
    +---------+--------------+------+-----+---------+-------+
    rows in set (0.00 sec)
    
    #方法三:在所有字段后单独定义primary key
    create table department3(
    id int,
    name varchar(20),
    comment varchar(100),
    constraint pk_name primary key(id); #创建主键并为其命名pk_name
    
    mysql> desc department3;
    +---------+--------------+------+-----+---------+-------+
    | Field   | Type         | Null | Key | Default | Extra |
    +---------+--------------+------+-----+---------+-------+
    | id      | int(11)      | NO   | PRI | NULL    |       |
    | name    | varchar(20)  | YES  |     | NULL    |       |
    | comment | varchar(100) | YES  |     | NULL    |       |
    +---------+--------------+------+-----+---------+-------+
    rows in set (0.01 sec)
    
    

      

    多列做主键:

    ==================多列做主键================
    create table service(
    ip varchar(15),
    port char(5),
    service_name varchar(10) not null,
    primary key(ip,port)
    );
    
    
    mysql> desc service;
    +--------------+-------------+------+-----+---------+-------+
    | Field        | Type        | Null | Key | Default | Extra |
    +--------------+-------------+------+-----+---------+-------+
    | ip           | varchar(15) | NO   | PRI | NULL    |       |
    | port         | char(5)     | NO   | PRI | NULL    |       |
    | service_name | varchar(10) | NO   |     | NULL    |       |
    +--------------+-------------+------+-----+---------+-------+
    rows in set (0.00 sec)
    
    mysql> insert into service values
        -> ('172.16.45.10','3306','mysqld'),
        -> ('172.16.45.11','3306','mariadb')
        -> ;
    Query OK, 2 rows affected (0.00 sec)
    Records: 2  Duplicates: 0  Warnings: 0
    
    mysql> insert into service values ('172.16.45.10','3306','nginx');
    ERROR 1062 (23000): Duplicate entry '172.16.45.10-3306' for key 'PRIMARY'
    

      

    auto_increment

    步长increment与起始偏移量offset:auto_increment_increment,auto_increment_offset

    --------偏移量:auto_increment_offset---------
    ==============没有设置偏移量的时候
    create table dep(
    id int primary key auto_increment,
    name char(10)
    );
    insert into dep(name) values('IT'),('HR'),('EFO');
    select * from dep;
    
    ================设置自增的时候以10开头
    create table dep1(
    id int primary key auto_increment,
    name char(10)
    )auto_increment = 10;
    insert into dep1(name) values('IT'),('HR'),('EFO');
    select * from dep1;
    
    ===============auto_increment_increment:自增步长
    create table dep3(
    id int primary key auto_increment,
     name char(10)
    );
    会话:通过客户端连到服务端(一次链接称为一次会话)
    set session auto_increment_increment = 2; #会话级,只对当前会话有效
    set global auto_increment_increment=2; #全局,对所有的会话都有效
    insert into dep3(name) values('IT'),('HR'),('SALE'),('Boss');
    
    -----------查看变量----------
    show variables like '%auto_in%';#查看变量。只要包含auto_in就都查出来了
    
    =========auto_increment_offset:偏移量+auto_increment_increment:步长===========
    注意:如果auto_increment_offset的值大于auto_increment_increment的值,
    则auto_increment_offset的值会被忽略
    
    set session auto_increment_offset=2;
    set session auto_increment_increment=3;
    show variables like '%auto_in%';
    
    create table dep4(
    id int primary key auto_increment,
    name char(10)
    );
    insert into dep4(name) values('IT'),('HR'),('SALE'),('Boss');
    

      

    foreign key (外键约束)

    快速理解foreign key

    员工信息表有三个字段:工号  姓名  部门

    公司有3个部门,但是有1个亿的员工,那意味着部门这个字段需要重复存储,部门名字越长,越浪费

    解决方法:

    我们完全可以定义一个部门表

    然后让员工信息表关联该表,如何关联,即foreign key

    #表类型必须是innodb存储引擎,且被关联的字段,即references指定的另外一个表的字段,必须保证唯一
    create table department(
    id int primary key,
    name varchar(20) not null
    )engine=innodb;
    
    #dpt_id外键,关联父表(department主键id),同步更新,同步删除
    create table employee(
    id int primary key,
    name varchar(20) not null,
    dpt_id int,
    constraint fk_name foreign key(dpt_id)
    references department(id)
    on delete cascade
    on update cascade 
    )engine=innodb;
    
    
    #先往父表department中插入记录
    insert into department values
    (1,'欧德博爱技术有限事业部'),
    (2,'艾利克斯人力资源部'),
    (3,'销售部');
    
    
    #再往子表employee中插入记录
    insert into employee values
    (1,'egon',1),
    (2,'alex1',2),
    (3,'alex2',2),
    (4,'alex3',2),
    (5,'李坦克',3),
    (6,'刘飞机',3),
    (7,'张火箭',3),
    (8,'林子弹',3),
    (9,'加特林',3)
    ;
    
    
    #删父表department,子表employee中对应的记录跟着删
    mysql> delete from department where id=3;
    mysql> select * from employee;
    +----+-------+--------+
    | id | name  | dpt_id |
    +----+-------+--------+
    |  1 | egon  |      1 |
    |  2 | alex1 |      2 |
    |  3 | alex2 |      2 |
    |  4 | alex3 |      2 |
    +----+-------+--------+
    
    
    #更新父表department,子表employee中对应的记录跟着改
    mysql> update department set id=22222 where id=2;
    mysql> select * from employee;
    +----+-------+--------+
    | id | name  | dpt_id |
    +----+-------+--------+
    |  1 | egon  |      1 |
    |  3 | alex2 |  22222 |
    |  4 | alex3 |  22222 |
    |  5 | alex1 |  22222 |
    +----+-------+--------+
    

    如何找出两张表之间的关系 

    分析步骤:
    #1、先站在左表的角度去找
    是否左表的多条记录可以对应右表的一条记录,如果是,则证明左表的一个字段foreign key 右表一个字段(通常是id)
    
    #2、再站在右表的角度去找
    是否右表的多条记录可以对应左表的一条记录,如果是,则证明右表的一个字段foreign key 左表一个字段(通常是id)
    
    #3、总结:
    #多对一:
    如果只有步骤1成立,则是左表多对一右表
    如果只有步骤2成立,则是右表多对一左表
    
    #多对多
    如果步骤1和2同时成立,则证明这两张表时一个双向的多对一,即多对多,需要定义一个这两张表的关系表来专门存放二者的关系
    
    #一对一:
    如果1和2都不成立,而是左表的一条记录唯一对应右表的一条记录,反之亦然。这种情况很简单,就是在左表foreign key右表的基础上,将左表的外键字段设置成unique即可
    

     举例

    #一对多或称为多对一
    三张表:出版社,作者信息,书
    
    一对多(或多对一):一个出版社可以出版多本书
    关联方式:foreign key
    
    多对多:一个作者可以写多本书,一本书也可以有多个作者,双向的一对多,即多对多
      
    关联方式:foreign key+一张新的表
    
    #一对一
    两张表:学生表和客户表
    
    一对一:一个学生是一个客户,一个客户有可能变成一个学生,即一对一的关系
    
    关联方式:foreign key+unique
    
  • 相关阅读:
    Codeforces Round #256 (Div. 2/B)/Codeforces448B_Suffix Structures(字符串处理)
    【android】优秀的UI资源站点集合
    升级iOS8系统后,保险箱Pro、私人保险箱、私密相冊打开就闪退的官方解决方式
    js产生随机数
    java实现各种数据统计图(柱形图,饼图,折线图)
    Matlab画图-非常具体,非常全面
    Lucene教程具体解释
    NAND FLASH
    Jenkins(二)
    iOS 本地通知
  • 原文地址:https://www.cnblogs.com/xiao-apple36/p/9562767.html
Copyright © 2011-2022 走看看