2010-02-23 67 views
1
Create Table: CREATE TABLE `category` (
    `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, 
    `name` varchar(255) NOT NULL, 
    `parent` bigint(20) unsigned DEFAULT NULL, 
    PRIMARY KEY (`id`), 
    UNIQUE KEY `name` (`name`), 
    KEY `parent_idx` (`parent`), 
    CONSTRAINT `category_parent_category_id` FOREIGN KEY (`parent`) REFERENCES `category` (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 

我不确定外键是否意味着索引?此处是否需要“父”的索引?

编辑

我没有看到所谓指数:

mysql> show index from category; 
+----------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ 
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | 
+----------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ 
| category |   0 | PRIMARY |   1 | id   | A   |   0 |  NULL | NULL |  | BTREE  |   | 
| category |   0 | name  |   1 | name  | A   |   0 |  NULL | NULL |  | BTREE  |   | 
| category |   1 | parent_idx |   1 | parent  | A   |   0 |  NULL | NULL | YES | BTREE  |   | 
+----------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ 
3 rows in set (0.02 sec) 
+0

@ user198729:您没有看到另一个索引,因为如果您已经明确创建了外键,InnoDB不会为外键创建新索引。如果你不创建'parent_idx',InnoDB会为你创建一个(使用不同的名称)。 – 2010-02-23 13:46:31

回答

0

我不知道外键 是否意味着指数?

“InnoDB的需要外键索引和参考键,以便外键检查可以快速,不需要表扫描...这样的索引将在引用表中创建自动如果它不存在。” (Source

因此KEY parent_idx (parent)是多余的。

另一方面请注意,如果要使用ALTER TABLE语法添加外键约束,则必须先显式创建所需的索引。

+0

但是没有'show index from table'的索引 – user198729 2010-02-23 13:39:00

+0

您没有看到另一个索引,因为InnoDB不会为外键创建新的索引if你已经明确地创建了一个。如果你不创建'parent_idx',InnoDB会为你创建(使用不同的名称)。 – 2010-02-23 13:47:02

2

在SQL Server:外键不会自动创建索引。您需要在需要的位置显式创建索引。这是因为你不一定要索引每个FK,因为它会增加插入开销。

+2

不,InnoDB会自动创建一个索引:“InnoDB需要外键和引用键的索引,这样外键检查可以很快并且不需要表扫描......如果这样的索引是在引用表上自动创建的不存在。”资料来源:http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html。 SQL Server不会在外键上自动创建索引。 – 2010-02-23 13:25:18

+0

我想我只是假设他们会在这方面是一样的。 FWIW,我认为SQL Server的行为更好,因为它提供了更多的控制。 – 2010-02-23 14:47:08

相关问题