我对外键约束有疑问。所以我做了两个像这样的简单表格用于测试目的。
mysql> EXPLAIN parent;
+-------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
+-------+---------+------+-----+---------+----------------+
1 row in set (0.01 sec)
mysql> EXPLAIN child;
+-----------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| parent_id | int(11) | NO | MUL | NULL | |
+-----------+---------+------+-----+---------+----------------+
现在我在创建表时没有指定外键约束。我后来添加如下。
ALTER TABLE child
ADD CONSTRAINT parent_fk FOREIGN KEY(parent_id) REFERENCES parent(id);
我检查了engine
用于表格及其InnoDB
. 我的问题是...
为什么它不限制我删除父项中有多个依赖子记录的记录?默认情况下它应该限制我对吗?
如果我在添加外键约束之前在外键字段上创建索引,它会按预期工作。我每次都需要创建这样的索引吗?
- 在创建表后添加任何类型的约束是一种不好的做法吗?