【MySQL】FOREIGN KEY

1

1

  • FOREIGN KEY reference PRIMARY KEY
CREATE TABLE `roottb` (
`id` INT(11) UNSIGNED AUTO_INCREMENT NOT NULL,
`data` VARCHAR(100) NOT NULL DEFAULT ‘‘,
PRIMARY KEY (`id`)
) ENGINE =InnoDB;

CREATE TABLE `subtb` (
`id` INT(11) UNSIGNED AUTO_INCREMENT NOT NULL,
`rootid` INT(11) UNSIGNED NOT NULL DEFAULT ‘0‘,
`data` VARCHAR(100) NOT NULL DEFAULT ‘‘,
PRIMARY KEY (`id`),
INDEX (`rootid`),
FOREIGN KEY (`rootid`) REFERENCES roottb(`id`) ON DELETE CASCADE
) ENGINE =InnoDB;

插入数据,sub表的rootid使用root表中id的值

mysql> INSERT INTO `roottb` (`id`,`data`)
    -> VALUES (‘1‘, ‘test root line 1‘),
    -> (‘2‘, ‘test root line 2‘),
    -> (‘3‘, ‘test root line 3‘);
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql>
mysql> INSERT INTO `subtb` (`id`,`rootid`,`data`)
    -> VALUES (‘1‘, ‘1‘, ‘test sub line 1 for root 1‘),
    -> (‘2‘, ‘1‘, ‘test sub line 2 for root 1‘),
    -> (‘3‘, ‘1‘, ‘test sub line 3 for root 1‘),
    -> (‘4‘, ‘2‘, ‘test sub line 1 for root 2‘),
    -> (‘5‘, ‘2‘, ‘test sub line 2 for root 2‘),
    -> (‘6‘, ‘2‘, ‘test sub line 3 for root 2‘),
    -> (‘7‘, ‘3‘, ‘test sub line 1 for root 3‘),
    -> (‘8‘, ‘3‘, ‘test sub line 2 for root 3‘),
    -> (‘9‘, ‘3‘, ‘test sub line 3 for root 3‘);
Query OK, 9 rows affected (0.01 sec)
Records: 9  Duplicates: 0  Warnings: 0

mysql> select * from roottb;
+----+------------------+
| id | data             |
+----+------------------+
|  1 | test root line 1 |
|  2 | test root line 2 |
|  3 | test root line 3 |
+----+------------------+
3 rows in set (0.00 sec)
mysql> select * from subtb;
+----+--------+----------------------------+
| id | rootid | data                       |
+----+--------+----------------------------+
|  1 |      1 | test sub line 1 for root 1 |
|  2 |      1 | test sub line 2 for root 1 |
|  3 |      1 | test sub line 3 for root 1 |
|  4 |      2 | test sub line 1 for root 2 |
|  5 |      2 | test sub line 2 for root 2 |
|  6 |      2 | test sub line 3 for root 2 |
|  7 |      3 | test sub line 1 for root 3 |
|  8 |      3 | test sub line 2 for root 3 |
|  9 |      3 | test sub line 3 for root 3 |
+----+--------+----------------------------+
9 rows in set (0.00 sec)

插入数据,sub表的rootid使用非root表中id的值

mysql> INSERT INTO `subtb` (`id`,`rootid`,`data`)
    -> VALUES (‘10‘, ‘4‘, ‘test sub line 1 for root 4 not existed‘);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test`.`subtb`, CONSTRAINT `subtb_ibfk_1` FOREIGN KEY (`rootid`) REFERENCES `roottb` (`id`) ON DELETE CASCADE)
mysql> 
  • FOREIGN KEY reference UNIQUE KEY not primary
CREATE TABLE roottb3 (
id INT(11) UNSIGNED AUTO_INCREMENT NOT NULL,
rootdata varchar(100) NOT NULL,
 PRIMARY KEY (id),
 UNIQUE KEY(rootdata)
)ENGINE=InnoDB;

CREATE TABLE subtb3 (
id INT(11) UNSIGNED AUTO_INCREMENT NOT NULL,
subdata varchar(100) NOT NULL ,
PRIMARY KEY (id),
INDEX (subdata),
FOREIGN KEY (`subdata`) REFERENCES roottb3(`rootdata`) ON DELETE CASCADE on update CASCADE
)ENGINE =InnoDB;

INSERT INTO `roottb3` (`id`,`rootdata`)
VALUES (‘1‘, ‘aaa‘),
(‘2‘, ‘bbb‘),
(‘3‘, ‘ccc‘);

INSERT INTO `subtb3` (`id`,`subdata`)
VALUES (‘1‘, ‘aaa‘),
       (‘2‘, ‘aaa‘),
       (‘3‘, ‘aaa‘),
       (‘4‘, ‘bbb‘),
       (‘5‘, ‘bbb‘),
       (‘6‘, ‘bbb‘),
       (‘7‘, ‘ccc‘),
       (‘8‘, ‘ccc‘),
       (‘9‘, ‘ccc‘);
  • FOREIGN KEY  -- ON DELETE CASCADE on update CASCADE
  1. on update CASCADE

    mysql> select * from roottb3;
    +----+----------+
    | id | rootdata |
    +----+----------+
    |  1 | aaa      |
    |  2 | bbb      |
    |  3 | ccc      |
    +----+----------+
    3 rows in set (0.00 sec)
    
    mysql> select * from subtb3;
    +----+---------+
    | id | subdata |
    +----+---------+
    |  1 | aaa     |
    |  2 | aaa     |
    |  3 | aaa     |
    |  4 | bbb     |
    |  5 | bbb     |
    |  6 | bbb     |
    |  7 | ccc     |
    |  8 | ccc     |
    |  9 | ccc     |
    +----+---------+
    9 rows in set (0.00 sec)
    
    mysql> 
    
    mysql> update roottb3 set rootdata=‘ddd‘ where id =3;
    Query OK, 0 rows affected (0.01 sec)
    Rows matched: 1  Changed: 0  Warnings: 0
    
    mysql> select * from roottb3;
    +----+----------+
    | id | rootdata |
    +----+----------+
    |  1 | aaa      |
    |  2 | bbb      |
    |  3 | ddd      |
    +----+----------+
    3 rows in set (0.00 sec)
    
    mysql> select * from subtb3;
    +----+---------+
    | id | subdata |
    +----+---------+
    |  1 | aaa     |
    |  2 | aaa     |
    |  3 | aaa     |
    |  4 | bbb     |
    |  5 | bbb     |
    |  6 | bbb     |
    |  7 | ddd     |
    |  8 | ddd     |
    |  9 | ddd     |
    +----+---------+
    9 rows in set (0.00 sec)
  2. ON DELETE CASCADE

    mysql> delete from roottb3 where id=2;
    Query OK, 1 row affected (0.01 sec)
    
    mysql> select * from roottb3;
    +----+----------+
    | id | rootdata |
    +----+----------+
    |  1 | aaa      |
    |  3 | ddd      |
    +----+----------+
    2 rows in set (0.00 sec)
    
    mysql> select * from subtb3;
    +----+---------+
    | id | subdata |
    +----+---------+
    |  1 | aaa     |
    |  2 | aaa     |
    |  3 | aaa     |
    |  7 | ddd     |
    |  8 | ddd     |
    |  9 | ddd     |
    +----+---------+
    6 rows in set (0.00 sec)
    
    mysql> 

    3. delete subtb data

    mysql> select * from subtb3;
    +----+---------+
    | id | subdata |
    +----+---------+
    |  1 | aaa     |
    |  2 | aaa     |
    |  3 | aaa     |
    |  7 | ddd     |
    |  8 | ddd     |
    |  9 | ddd     |
    +----+---------+
    6 rows in set (0.00 sec)
    
    mysql> delete from subtb3 where id=9;
    Query OK, 1 row affected (0.03 sec)
    
    mysql> 

    4. insert and delete the data of roottb that not used by subtable

    mysql> select * from roottb3;
    +----+----------+
    | id | rootdata |
    +----+----------+
    |  1 | aaa      |
    |  3 | ddd      |
    +----+----------+
    2 rows in set (0.00 sec)
    
    mysql> INSERT INTO `roottb3` (`id`,`data`) VALUES (‘5‘, ‘eeee‘),(‘6‘, ‘ffff‘);
    ERROR 1054 (42S22): Unknown column ‘data‘ in ‘field list‘
    mysql> INSERT INTO `roottb3` (`id`,`rootdata`) VALUES (‘5‘, ‘eeee‘),(‘6‘, ‘ffff‘);
    Query OK, 2 rows affected (0.01 sec)
    Records: 2  Duplicates: 0  Warnings: 0
    
    mysql> select * from roottb3;
    +----+----------+
    | id | rootdata |
    +----+----------+
    |  1 | aaa      |
    |  3 | ddd      |
    |  5 | eeee     |
    |  6 | ffff     |
    +----+----------+
    4 rows in set (0.00 sec)
    
    mysql> delete from table roottb3 where rootdata = ‘ffff‘;
    ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘table roottb3 where rootdata = ‘ffff‘‘ at line 1
    mysql> delete from  roottb3 where rootdata = ‘ffff‘;
    Query OK, 1 row affected (0.01 sec)
    
    mysql> select * from roottb3;
    +----+----------+
    | id | rootdata |
    +----+----------+
    |  1 | aaa      |
    |  3 | ddd      |
    |  5 | eeee     |
    +----+----------+
    3 rows in set (0.00 sec)
    
    mysql> 

     

  • if without ON DELETE CASCADE on update CASCADE
 CREATE TABLE roottb4 (
id INT(11) UNSIGNED AUTO_INCREMENT NOT NULL,
rootdata varchar(100) NOT NULL,
 PRIMARY KEY (id),
 UNIQUE KEY(rootdata)
)ENGINE=InnoDB;

CREATE TABLE subtb4 (
id INT(11) UNSIGNED AUTO_INCREMENT NOT NULL,
subdata varchar(100) NOT NULL ,
PRIMARY KEY (id),
INDEX (subdata),
FOREIGN KEY (`subdata`) REFERENCES roottb4(`rootdata`)
)ENGINE =InnoDB;

INSERT INTO `roottb4` (`id`,`rootdata`)
VALUES (‘1‘, ‘aaa‘),
(‘2‘, ‘bbb‘),
(‘3‘, ‘ccc‘);

INSERT INTO `subtb4` (`id`,`subdata`)
VALUES (‘1‘, ‘aaa‘),
       (‘2‘, ‘aaa‘),
       (‘3‘, ‘aaa‘),
       (‘4‘, ‘bbb‘),
       (‘5‘, ‘bbb‘),
       (‘6‘, ‘bbb‘),
       (‘7‘, ‘ccc‘),
       (‘8‘, ‘ccc‘),
       (‘9‘, ‘ccc‘);

result

mysql>
mysql> select * from roottb4;
+----+----------+
| id | rootdata |
+----+----------+
|  1 | aaa      |
|  2 | bbb      |
|  3 | ccc      |
+----+----------+
3 rows in set (0.00 sec)

mysql> select * from subtb4;
+----+---------+
| id | subdata |
+----+---------+
|  1 | aaa     |
|  2 | aaa     |
|  3 | aaa     |
|  4 | bbb     |
|  5 | bbb     |
|  6 | bbb     |
|  7 | ccc     |
|  8 | ccc     |
|  9 | ccc     |
+----+---------+
9 rows in set (0.00 sec)

mysql>
mysql>
mysql> update roottb4 set rootdata = ‘ddd‘ where id = 3;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`test`.`subtb4`, CONSTRAINT `subtb4_ibfk_1` FOREIGN KEY (`subdata`) REFERENCES `roottb4` (`rootdata`))
mysql>
mysql> delete from roottb4 where id =3;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`test`.`subtb4`, CONSTRAINT `subtb4_ibfk_1` FOREIGN KEY (`subdata`) REFERENCES `roottb4` (`rootdata`))
mysql> 
时间: 2024-10-09 18:53:59

【MySQL】FOREIGN KEY的相关文章

【MySQL】结构行长度的一些限制

今天被开发提交的DDL变更再次困惑,表中字段较多,希望将已有的两个varchar(4000)字段改为varchar(20000),我想innodb对varchar的存储不就是取前768字节记录当前行空间嘛,所以变更不会有任何问题的,但铁打的事实给了我结结实实的一个巴掌,直接报错,现在回放下这个错误! 模拟测试: CREATE TABLE `ttt` ( `id` DOUBLE , `select_type` VARCHAR (57), `table` VARCHAR (192), `type`

【MySql】性能优化之分析命令

[MySql]性能优化之分析命令     一 当发现程序运行比较慢的时候,首先排除物力资源问题之后,就将注意力转向mysq数据库: 1.首先确定运行慢的sql语句: mysql> show full processlist; 2.确认低效的查询: 多次执行第一步发现time耗费大的sql语句.查看耗费的时间. 3.为sql生成一个执行计划query Execution plan(QEP) mysql> explain select * from tbal_name where ...; 4.查

【MySQL】【ProxySQL】浅析mysql_users表

[MySQL][ProxySQL]浅析mysql_users表 1.表定义与字段说明 表的DDL定义: CREATE TABLE mysql_users ( username VARCHAR NOT NULL, #用户名 password VARCHAR, #密码 active INT CHECK (active IN (0,1)) NOT NULL DEFAULT 1, #是否启用 use_ssl INT CHECK (use_ssl IN (0,1)) NOT NULL DEFAULT 0,

【MySQL】Unknown column 'column_name' in 'field list'

使用 INSERT INTO - SELECT FROM - ON DUPLICATE KEY UPDATE 时遇到了这个问题,百思不得其解?? 后来总算找到了解决方法,使用子查询.如下: 参考链接:https://stackoverflow.com/questions/2472229/insert-into-select-from-on-duplicate-key-update [MySQL]Unknown column 'column_name' in 'field list' 原文地址:h

【Mysql】Mysql的安装、部署与图形化

Mysql是一个必须学会如何安装与部署的工具,它不同于其它那些傻瓜式的应用/程序,一键到底,如果是初次在Windows下安装Mysql的初学者还是有一定难度的. 本文配合之前的<[Javaweb]前台开发环境的配置Myeclipse6.5+JDK1.6+Tomcat6.0+SVN1.8>(点击打开链接)一文中的前台开发环境的部署,也就形成了JavaWeb.JSP.J2EE的基本开发环境. 一.Mysql的下载 首先打开Mysql的官网(点击打开链接),百度一下是搜不到的,我也找了很久才找到My

【Mysql】常用指令之——忘记密码

上一篇文章基本总结了下myql下通过指令怎么创建用户,详见:[Mysql]常用指令之--用户操作(创建,授权,修改,删除) 今天说下特殊情况,忘记密码了怎么办??? 重装,删除配置等可以完成此操作.那不重装怎么办呢? 原理: 通过增加启动参数:--skip-grant-tables 跳过grant-tables启动数据库,这样就不需要密码就能进去了. 下面来玩玩: linux下: 1.关闭mysql进程,应该都会哈比如:service mysql stop 或者 ps -ef | grep my

FluentData -Micro ORM with a fluent API that makes it simple to query a database 【MYSQL】

官方地址:http://fluentdata.codeplex.com/documentation MYSQL: MySQL through the MySQL Connector .NET driver. 连接字符串:Server=127.0.0.1;Database=testDB;Uid=root;Pwd=jnex;<system.data> <DbProviderFactories> <add name="MySQL Data Provider" i

【MYSQL】Mysql 设备选型与系统规划-实战参考文档-带附件-可下载

更多精彩内容尽在www.leonarding.com <Mysql 设备选型与系统规划> 引言:项目的设备选型是一项细腻而又艰巨的任务.因为它有一次性.不可更改.兼容性.扩展性.功能性.性能性.易用性等参数阀值来参照.例如我们的项目,首先要了解今年的设备采购预算有多少,如何分配的,分配下来每个项目大概有多少,按照预算标准进行分级.其次由于我们是金融企业采购范围是有所限制的,会有一个备选目录,上面列举了品牌.厂家.规格等信息,只能在这些目录中选择,如果设备有超出目录的需要写说明申请. 再次就需要

【Mysql】经常使用指令之——忘记password

上一篇文章基本总结了下myql下通过指令怎么创建用户.详见:[Mysql]经常使用指令之--用户操作(创建,授权,改动.删除) 今天说下特殊情况,忘记password了怎么办??? 重装.删除配置等能够完毕此操作.那不重装怎么办呢? 原理: 通过添加启动參数:--skip-grant-tables 跳过grant-tables启动数据库,这样就不须要password就能进去了. 以下来玩玩: linux下: 1.关闭mysql进程.应该都会哈比方:service mysql stop 或者 ps