在复合主键

时间:2018-01-05 20:53:05

标签: mysql foreign-keys primary-key

CREATE TABLE test
(
  user_id int unsigned not null,
  post_id int unsigned not null,
  primary key (user_id, post_id),
  foreign key test_user_id (user_id) references user (id),
  foreign key test_post_id (post_id) references post (id)
);

show index from test;

+-------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name     | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| test  |          0 | PRIMARY      |            1 | user_id     | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
| test  |          0 | PRIMARY      |            2 | post_id     | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
| test  |          1 | test_post_id |            1 | post_id     | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
+-------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

添加id列作为主键产生:

show index from test;

+-------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name     | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| test  |          0 | PRIMARY      |            1 | id          | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
| test  |          1 | test_user_id |            1 | user_id     | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
| test  |          1 | test_post_id |            1 | post_id     | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
+-------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

当使用由外键约束中使用的列组成的复合主键时,似乎未创建索引test_user_id。应该是这样的吗?有办法克服这个问题吗? (MySQL 5.7)

1 个答案:

答案 0 :(得分:2)

创建FOREIGN KEY约束时,必须有一个索引。如果有必要,创建FOREIGN KEY将自动创建一个新索引(至少从一些旧版本的MySQL开始,比如4.0或者其他东西,但是一次,甚至旧的版本都没有自动创建FK索引IIRC )。

但是如果已经存在合适的索引,MySQL不需要创建新索引。 InnoDB至少是那么聪明。

任何包含FK列作为索引最左侧子集的索引都将满足要求。 PRIMARY KEY索引(即表的聚簇索引)工作正常。