同一列可以对另一列具有主键和外键约束吗?
Table1: ID - Primary column, foreign key constraint for Table2 ID Table2: ID - Primary column, Name
如果我尝试删除table1数据,这会成为问题吗?
Delete from table1 where ID=1000;
谢谢。
这应该没有问题。考虑以下示例:
CREATE TABLE table2 ( id int PRIMARY KEY, name varchar(20) ) ENGINE=INNODB; CREATE TABLE table1 ( id int PRIMARY KEY, t2_id int, FOREIGN KEY (t2_id) REFERENCES table2 (id) ) ENGINE=INNODB; INSERT INTO table2 VALUES (1, 'First Row'); INSERT INTO table2 VALUES (2, 'Second Row'); INSERT INTO table1 VALUES (1, 1); INSERT INTO table1 VALUES (2, 1); INSERT INTO table1 VALUES (3, 1); INSERT INTO table1 VALUES (4, 2);
这些表现在包含:
SELECT * FROM table1; +----+-------+ | id | t2_id | +----+-------+ | 1 | 1 | | 2 | 1 | | 3 | 1 | | 4 | 2 | +----+-------+ 4 rows in set (0.00 sec) SELECT * FROM table2; +----+------------+ | id | name | +----+------------+ | 1 | First Row | | 2 | Second Row | +----+------------+ 2 rows in set (0.00 sec)
现在我们可以成功删除这样的行:
DELETE FROM table1 WHERE id = 1; Query OK, 1 row affected (0.00 sec) DELETE FROM table1 WHERE t2_id = 2; Query OK, 1 row affected (0.00 sec)
但是,我们将无法删除以下内容:
DELETE FROM table2 WHERE id = 1; ERROR 1451 (23000): A foreign key constraint fails
如果我们table1使用CASCADE选项定义了外键,那么我们将能够删除父项,并且所有子项都将被自动删除:
table1
CASCADE
CREATE TABLE table2 ( id int PRIMARY KEY, name varchar(20) ) ENGINE=INNODB; CREATE TABLE table1 ( id int PRIMARY KEY, t2_id int, FOREIGN KEY (t2_id) REFERENCES table2 (id) ON DELETE CASCADE ) ENGINE=INNODB; INSERT INTO table2 VALUES (1, 'First Row'); INSERT INTO table2 VALUES (2, 'Second Row'); INSERT INTO table1 VALUES (1, 1); INSERT INTO table1 VALUES (2, 1); INSERT INTO table1 VALUES (3, 1); INSERT INTO table1 VALUES (4, 2);
如果我们要重复之前失败的操作DELETE,table1则将删除其中的子行以及其中的父行table2:
DELETE
table2
DELETE FROM table2 WHERE id = 1; Query OK, 1 row affected (0.00 sec) SELECT * FROM table1; +----+-------+ | id | t2_id | +----+-------+ | 4 | 2 | +----+-------+ 1 row in set (0.00 sec) SELECT * FROM table2; +----+------------+ | id | name | +----+------------+ | 2 | Second Row | +----+------------+ 1 row in set (0.00 sec)