mysql 创建外键sql语句、(例子测试验证
MySQL创建外键
CREATE TABLE Members (
???? Member_ID INT NOT
NULL,
????
PRIMARY KEY AUTO_INCREMENT,
???? First_Name VARCHAR(30) NOT NULL,
???? Last_Name VARCHAR(30) NOT NULL,
????
Bday DATE NOT NULL,
???? Gender ENUM('M', 'F') DEFAULT 'F'
);
CREATE TABLE Email (
????? Email VARCHAR(50),
????? Member_ID INT NOT NULL,
????? PRIMARY KEY
(Email, Member_ID),
?????
CONSTRAINT FOREIGN KEY (Member_ID) REFERENCES Members(Member_ID)
????? ON DELETE? RESTRICT? ON UPDATE CASCADE
);
?
在
MySQL
中只有
InnoDB
类型的表才支持外键与存储过程
所有要建立外键的字段必须建立索引
?
首先,目前在产品环境可用的MySQL
版本(指4.0.x
和4.1.x
)中,只有InnoDB
引擎才允许使用外键,所以,我们的数据表必须使用InnoDB
引擎。
下面,我们先创建以下测试用数据库表:
CODE:[Copy to clipboard]CREATE TABLE `roottb` (
`id` INT(11) UNSIGNED AUTO_INCREMENT NOT NULL,
`data` VARCHAR(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) TYPE=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
) TYPE=InnoDB;
注意:
1
、必须使用InnoDB
引擎;
2
、外键必须建立索引(INDEX
);
3
、外键绑定关系这里使用了“ ON DELETE CASCADE”
,意思是如果外键对应数据被删除,将关联数据完全删除,更多信息请参考MySQL
手册中关于InnoDB
的文档;
好,接着我们再来插入测试数据:
CODE:[Copy to clipboard]INSERT INTO `roottb` (`id`,`data`)
VALUES ('1', 'test root line 1'),
('2', 'test root line 2'),
('3', 'test root line 3');
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');
我们先看一下当前数据表的状态:
CODE:[Copy to clipboard]mysql>; show tables;
+----------------+
| Tables_in_test |
+----------------+
| roottb |
| subtb |
+----------------+
2 rows in set (0.00 sec)
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.05 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 |