2

In have a many-to-many linking table and I'm trying to set up two foreign keys on it. I run these two statements:

ALTER TABLE address_list_memberships
ADD CONSTRAINT fk_address_list_memberships_address_id
FOREIGN KEY index_address_id (address_id)
REFERENCES addresses (id);

ALTER TABLE address_list_memberships
ADD CONSTRAINT fk_address_list_memberships_list_id
FOREIGN KEY index_list_id (list_id)
REFERENCES lists (id);

I would expect that when I run SHOW CREATE TABLE address_list_memberships I'd see this:

[...]
KEY `index_address_id` (`address_id`),
KEY `index_list_id` (`list_id`),
CONSTRAINT `fk_address_list_memberships_list_id` FOREIGN KEY (`list_id`) 
    REFERENCES `lists` (`id`),
CONSTRAINT `fk_address_list_memberships_address_id` FOREIGN KEY (`address_id`) 
    REFERENCES `addresses` (`id`)

But instead I get this:

[...]
KEY `index_list_id` (`list_id`),
CONSTRAINT `fk_address_list_memberships_list_id` FOREIGN KEY (`list_id`) 
    REFERENCES `lists` (`id`),
CONSTRAINT `fk_address_list_memberships_address_id` FOREIGN KEY (`address_id`) 
    REFERENCES `addresses` (`id`)

It looks as though only one index is there. Seems to contradict the MySQL docs which say MySQL automatically creates an index on the referencing column whenever you create a foreign key.

I've noticed this only-one-index thing every time I create two FKs on a table whether I use a GUI tool such as CocoaMySQL or SQLyog, or whether I do it on the command line.

Any illumination of this mystery would be very much appreciated.

4

2 回答 2

2

我刚试过,对我来说效果很好。我复制并粘贴了ALTER你写的陈述,这是我得到的:

mysql> show create table address_list_memberships;

CREATE TABLE `address_list_memberships` (
  `address_id` bigint(20) unsigned NOT NULL,
  `list_id` bigint(20) unsigned NOT NULL,
  KEY `index_address_id` (`address_id`),
  KEY `index_list_id` (`list_id`),
  CONSTRAINT `fk_address_list_memberships_list_id` 
    FOREIGN KEY (`list_id`) REFERENCES `lists` (`id`),
  CONSTRAINT `fk_address_list_memberships_address_id` 
    FOREIGN KEY (`address_id`) REFERENCES `addresses` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

我在 Mac OS X 上使用 MySQL 5.0.51a。

编辑: 尝试以下查询以获取 MySQL认为您的表上存在的所有索引:

SELECT * FROM information_schema.key_column_usage 
WHERE table_schema = 'test' AND table_name = 'address_list_memberships'\G

(我使用“测试”数据库进行测试;您应该将此字符串替换为定义表的模式的名称。)

于 2008-11-25T00:59:48.607 回答
0

这并不重要。您仍然在 list_id 上有一个索引。MySQL 要求任何外键约束在引用字段上也有索引。由于 index_list_id 和 fk_address_list_memberships_list_id 都是建立在 list_id 上的,MySQL 可能会看到这一点并使用 index_list_id 作为索引,将其重命名为 fk_address_list_memberships_list_id。您甚至可以跳过声明索引,因为 MySQL 会在您使用的版本中隐式执行它。

于 2009-07-12T14:08:40.450 回答