我创建了一个带有唯一索引和外部索引的表。当我添加唯一键时,我从 MySQL 得到了成功响应。然后,当我添加外键时,我也得到了成功响应。
以下是添加外键的 SQL:
ALTER TABLE `rewards_customer_index_points`
ADD CONSTRAINT FOREIGN KEY FK_CUSTOMER_INDEX_POINTS_CUSTOMER_ID( `customer_id` )
REFERENCES `customer_entity` ( `entity_id` )
ON DELETE CASCADE
ON UPDATE CASCADE
但是,我没有在表上看到该外键,因此看起来它没有创建成功。但它肯定在那里,因为当我删除引用的 customer_entity 记录时,级联会起作用。
为什么它没有显示在我的索引列表中?两个表都是 InnoDB。
这是表结构和表上的键:
mysql> explain rewards_customer_index_points;
+-----------------+------------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+------------------+------+-----+-------------------+-----------------------------+
| index_points_id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| customer_id | int(10) unsigned | NO | MUL | NULL | |
| status | int(11) | NO | | 0 | |
| points_positive | int(11) | NO | | NULL | |
| points_negative | int(11) | NO | | NULL | |
| updated_at | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-----------------+------------------+------+-----+-------------------+-----------------------------+
show index from rewards_customer_index_points;
+-------------------------------+------------+------------------------+--------------+-----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------------------------------+------------+------------------------+--------------+-----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| rewards_customer_index_points | 0 | PRIMARY | 1 | index_points_id | A | 2 | NULL | NULL | | BTREE | | |
| rewards_customer_index_points | 0 | idx_customer_id_status | 1 | customer_id | A | 2 | NULL | NULL | | BTREE | | |
| rewards_customer_index_points | 0 | idx_customer_id_status | 2 | status | A | 2 | NULL | NULL | | BTREE | | |
+-------------------------------+------------+------------------------+--------------+-----------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
最佳答案
首先,外键和唯一约束不是索引,它们是约束。但为了有效地实现此类约束,大多数 DBMS 使用索引。
在 MySQL 中,UNIQUE KEY
和 UNIQUE INDEX
在表定义中是同一件事,它们的意思是:添加索引和唯一约束。
对于外键,情况有点不同。在 InnoDB 引擎中,当您添加 FOREIGN KEY
约束时,会在引用列上创建索引,但前提是索引尚不存在。
您有 idx_customer_id_status
索引,它是一个 (customer_id, status)
复合索引,该索引可用于外键约束。因此,没有创建额外的索引。
关于mysql - 我没有看到我创建的外键索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9707386/