zoukankan      html  css  js  c++  java
  • DDL-级联删除

    #查看有没有索引:主键、外键、唯一键
    SHOW INDEX FROM major;
    SHOW INDEX FROM stuinfo;
    
    #删除外键
    ALTER TABLE stuinfo DROP FOREIGN KEY fk_stu_major;
    
    #传统的方式添加外键
    ALTER TABLE    stuinfo
    ADD CONSTRAINT fk_stu_major FOREIGN KEY(majorid) REFERENCES major(id);
    
    #查看表中有没有数据
    SELECT * FROM major;
    
    #插入数据
    INSERT INTO major
    VALUES (1,'java'),(2,'H5'),(3,'大数据');
    
    #查看表中有没有数据
    SELECT * FROM stuinfo;
    
    #插入数据
    INSERT INTO stuinfo
    SELECT 1,'john1','',NULL,NULL,1 UNION ALL
    SELECT 2,'john2','',NULL,NULL,1 UNION ALL
    SELECT 3,'john3','',NULL,NULL,2 UNION ALL
    SELECT 4,'john4','',NULL,NULL,2 UNION ALL
    SELECT 5,'john5','',NULL,NULL,1 UNION ALL
    SELECT 6,'john6','',NULL,NULL,3 UNION ALL
    SELECT 7,'john7','',NULL,NULL,3 UNION ALL
    SELECT 8,'john8','',NULL,NULL,1 ;
    
    #删除专业表中的三号专业
    DELETE FROM major WHERE id=3;

    #row: a
    foreign key 。出错有一个外键

    有两种方式解决

    方式一:级联删除,把相关的都删了
    比如删除专业把学员也删了
    #在原来添加外键的基础上,追加ON DELETE CASCADE

    方式二:级联置空
    比如把专业删了,专业那一栏就为空
    #在原来添加外键的基础上,追加ON DELETE SET NULL

    方式一:级联删除,把相关的都删了

    #首先,把原来的外键删一遍
    ALTER TABLE stuinfo DROP FOREIGN KEY fk_stu_major;
    
    #然后,添加级联删除的外键
    ALTER TABLE    stuinfo ADD CONSTRAINT fk_stu_major 
    FOREIGN KEY(majorid) REFERENCES major(id) 
    ON DELETE CASCADE;
    #在原来添加外键的基础上,追加ON DELETE CASCADE
    
    #最后,删除专业表的3号专业
    DELETE FROM major WHERE id=3;
    #删除完专业,学员信息也没了

    方式二:级联置空

    #首先,把原来的外键删一遍
    ALTER TABLE stuinfo DROP FOREIGN KEY fk_stu_major;
    
    #然后,添加级联置空的外键
    ALTER TABLE    stuinfo ADD CONSTRAINT fk_stu_major 
    FOREIGN KEY(majorid) REFERENCES major(id) 
    ON DELETE SET NULL;
    #在原来添加外键的基础上,追加ON DELETE SET NULL
    
    #最后,删除专业表的3号专业
    DELETE FROM major WHERE id=2;
    #删除完专业,学员信息专业的那一栏,引用为空
  • 相关阅读:
    【复习笔记】数据结构-外排序
    【复习笔记】数据结构-内排序
    python os
    pyinstaller problem
    python tk Lable
    机器学习
    python pickle and json
    pycharm 快捷键
    day10_procession作业
    python fibonacci recursion review
  • 原文地址:https://www.cnblogs.com/rijiyuelei/p/12381041.html
Copyright © 2011-2022 走看看