mysql如何处理外码约束
http://hi.baidu.com/wangzhiqing999/item/e74b2be28be445a3c00d7528
MySQL 外键约束
-- 创建测试主表. ID 是主键.
CREATE TABLE test_main (
id INT,
value VARCHAR(10),
PRIMARY KEY(id)
);
-- 创建测试子表.
CREATE TABLE test_sub (
id INT,
main_id INT,
value VARCHAR(10),
PRIMARY KEY(id)
);
-- 插入测试主表数据.
INSERT INTO test_main(id, value) VALUES (1, 'ONE');
INSERT INTO test_main(id, value) VALUES (2, 'TWO');
-- 插入测试子表数据.
INSERT INTO test_sub(id, main_id, value) VALUES (1, 1, 'ONEONE');
INSERT INTO test_sub(id, main_id, value) VALUES (2, 2, 'TWOTWO');
默认外键约束方式
mysql> ALTER TABLE test_sub
-> ADD CONSTRAINT main_id_cons
-> FOREIGN KEY (main_id)
-> REFERENCES test_main(id);
-> //
Query OK, 2 rows affected (0.17 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> DELETE FROM
-> test_main
-> WHERE
-> id = 1;
-> //
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constrai
nt fails (`test`.`test_sub`, CONSTRAINT `main_id_cons` FOREIGN KEY (`main_id`) R
EFERENCES `test_main` (`id`))
MySQL使用下面这个语句删除外键约束
ALTER TABLE test_sub DROP FOREIGN KEY main_id_cons;
DELETE CASCADE 方式
mysql> ALTER TABLE test_sub
-> ADD CONSTRAINT main_id_cons
-> FOREIGN KEY (main_id)
-> REFERENCES test_main(id)
-> ON DELETE CASCADE//
Query OK, 2 rows affected (0.16 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> DELETE FROM
-> test_main
-> WHERE
-> id = 1;
-> //
Query OK, 1 row affected (0.02 sec)
mysql> SELECT
-> *
-> FROM
-> test_sub;
-> //
+----+---------+--------+
| id | main_id | value |
+----+---------+--------+
| 2 | 2 | TWOTWO |
+----+---------+--------+
1 row in set (0.00 sec)
MySQL使用下面这个语句删除外键约束
ALTER TABLE test_sub DROP FOREIGN KEY main_id_cons;
UPDATE CASCADE方式
mysql> ALTER TABLE test_sub
-> ADD CONSTRAINT main_id_cons
-> FOREIGN KEY (main_id)
-> REFERENCES test_main(id)
-> ON UPDATE CASCADE;
-> //
Query OK, 1 row affected (0.14 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> UPDATE test_main SET id = 5 where id = 2
-> //
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from test_sub//
+----+---------+--------+
| id | main_id | value |
+----+---------+--------+
| 2 | 5 | TWOTWO |
+----+---------+--------+
1 row in set (0.00 sec)
MySQL使用下面这个语句删除外键约束
ALTER TABLE test_sub DROP FOREIGN KEY main_id_cons;
SET NULL方式
mysql> ALTER TABLE test_sub
-> ADD CONSTRAINT main_id_cons
-> FOREIGN KEY (main_id)
-> REFERENCES test_main(id)
-> ON DELETE SET NULL;
-> //
Query OK, 1 row affected (0.13 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> DELETE FROM
-> test_main
-> WHERE
-> id = 5;
-> //
Query OK, 1 row affected (0.05 sec)
mysql>
mysql> SELECT
-> *
-> FROM
-> test_sub;
-> //
+----+---------+--------+
| id | main_id | value |
+----+---------+--------+
| 2 | NULL | TWOTWO |
+----+---------+--------+
1 row in set (0.00 sec)