• mysql约束


    约束

    概念:约束是作用于表中字段上的规则,用于限制存储在表中的数据。

    目的:保证数据的正确、有效性和完整性。

    分类:

    非空约束:限制该字段的数据不能为null。        not null

    唯一约束:保证该字段所有的数据都是唯一不重复的。        unique

    主键约束:主键是一行数据的唯一标识,要求非空且唯一。        primary key

    默认约束:保存数据时,如果未指定该字段的值,则采用默认值。        default

    检查约束(8.016版本之后生效):保证字段满足某一个条件。        check

    外键约束:用来让两张表的数据建立连接,保证数据的一致性和完整性。foreign key

    注意:约束是作用于表中字段的,可以在建表或修改表时,添加约束。

    创建测试表验证

    create  table user(

        id int primary key auto_increment comment '主键',

        name varchar(10) not null unique comment '名字',

        age int check(age>0 && age<=120) comment '年龄',

        status char(1) default '1' comment '状态',

        gender char(1) comment '性别'

    ) comment '用户表';

    外键约束

    概念

    外键用来让两张表的数据之间建立连接,从而保证数据的一致性和完整性。

    删除/更新行为

    no action        当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新。(与restrict一致)

    restrict        当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新。(与no action一致)

    cascade                当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有,则也删除/更新外键在子表中的记录

    set null        当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有,则设置子表中该外键值为null(这就要求该外键允许取null)

    set default 父表有变更时,子表将外键列设置成一个默认的值(innodb不支持)

    语法

    alter table 表名 add constraint 外键名称 foreign key (外键字段) references 主表名(主表字段名) on update cascade on delete cascade;

    添加外键

    create table 表名(

    字段名 数据类型,

    [constraint][外键名称]foreign key(外键字段名) references 主表(主表列名));

    alter table 表名 add constraint 外键名称 foreign key(外键字段名) references 主表(主表列名);

    删除外键

    alter table 表名 drop foreign key 外键名称;

    创建部门表

    create table dept(

        id int auto_increment comment 'ID' primary key ,

        name varchar(10) not null comment '部门名称'

    ) comment '部门表';

    insert into dept (id,name) values (1,'研发部'),(2,'市场部'),(3,'财务部'),(4,'销售部'),(5,'总经办');

    创建员工表

    create table emp(

        id int auto_increment comment 'ID' primary key ,

        name varchar(10) not null comment '姓名',

        age int comment '年龄',

        job varchar(20) comment '职位',

        salary int comment '薪资',

        entrydate date comment '入职时间',

        managerid int comment '直属领导id',

        dept_id int  comment '部门id'

    ) comment '员工表';

    员工表数据插入

    insert into emp (id, name, age, job, salary, entrydate, managerid, dept_id)

    values (1,'金庸',45,'总裁',50000,'2000-10-12',null,5),

           (2,'杨逍',33,'开发',20000,'2005-10-21',1,1),

           (3,'张无忌',30,'项目经理',30000,'2008-11-12',1,1);

    创建外键验证

    alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id);

  • 相关阅读:
    【三维点云】CC教程1(Context Capture)
    关于 java 的动态绑定机制
    GLSL (2)数据类型
    判断点是否在点组成的封闭区域内c++
    递归解析Json,实现生成可视化Tree+快速获取JsonPath
    前端面试问题(3)
    读书笔记:《高频交易员》
    【JavaSE】继承与多态(下篇)
    Hadoop3:Yarn框架的三种调度算法
    vite+vue3 + ts 项目搭建——pinia
  • 原文地址:https://blog.csdn.net/yin_jia_jun/article/details/133500315