zoukankan      html  css  js  c++  java
  • 外键约束的参照操作

    实例一:

    mysql> CREATE TABLE users2(
    -> id SMALLINT PRIMARY KEY AUTO_INCREMENT,
    -> username VARCHAR(10) NOT NULL,
    -> pid SMALLINT UNSIGNED,
    -> FOREIGN KEY(pid) REFERENCES province (id) ON DELETE CASCADE
    -> );
    Query OK, 0 rows affected (0.13 sec)

    向父表写入记录

    mysql> INSERT province(pname) VALUES('A');
    Query OK, 1 row affected (0.07 sec)

    mysql> INSERT province(pname) VALUES('B');
    Query OK, 1 row affected (0.04 sec)

    mysql> INSERT province(pname) VALUES('C');
    Query OK, 1 row affected (0.22 sec)

    mysql> SELECT * FROM province;
    +----+-------+
    | id   |pname|
    +----+-------+
    | 1    | A      |
    | 2    | B      |
    | 3    | C      |
    +----+-------+
    3 rows in set (0.02 sec)

    向子表写入记录

    mysql> INSERT users2(username, pid) VALUES('Tom',3);
    Query OK, 1 row affected (0.07 sec)

    mysql> INSERT users2(username, pid) VALUES('John',7);
    ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint f
    ails (`test`.`users2`, CONSTRAINT `users2_ibfk_1` FOREIGN KEY (`pid`) REFERENCES
    `province` (`id`) ON DELETE CASCADE)
    mysql>
    mysql> INSERT users2(username, pid) VALUES('John',3);
    Query OK, 1 row affected (0.09 sec)

    mysql> SELECT * FROM users2;
    +----+----------+------+
    | id  |username| pid  |
    +----+----------+------+
    | 1   | Tom      | 3      |
    | 3   | John      | 3      |
    +----+----------+------+
    2 rows in set (0.00 sec)

    删除父表中的值,子表也会发生变化

    mysql> DELETE FROM province WHERE id=3;
    Query OK, 1 row affected (0.11 sec)

    mysql> SELECT * FROM province;
    +----+------- +
    | id  | pname |
    +--- +-- ----- +
    | 1   | A        |
    | 2   | B        |
    +----+------- +
    2 rows in set (0.00 sec)

    mysql> SELECT * FROM users2;
    Empty set (0.00 sec)

  • 相关阅读:
    transition
    Java自增陷阱
    不同编码格式中,字节和字符的关系
    表单重复提交
    source folder和package的区别
    @test 测试案例不能添加参数
    http协议content-type
    jdbc的缺点和mybatis的优点
    ==和equals的区别
    spring IOC和AOP
  • 原文地址:https://www.cnblogs.com/toudoubao/p/6600759.html
Copyright © 2011-2022 走看看