简体   繁体   English

MySQL - 唯一的外键

[英]MySQL - Unique foreign key

I have to make one of the foreign keys unique. 我必须使其中一个外键独一无二。 The problem is, I am getting the following message from the phpMyAdmin: 问题是,我从phpMyAdmin收到以下消息:

The following indexes appear to be equal and one of them should be removed: consignmentnumber_id_UNIQUE, fk_consignments_consignmentnumbers2

So my question is this: should I be bothered? 所以我的问题是:我应该被打扰吗? Is it really important not to have such indexes? 没有这样的索引真的很重要吗?

Every column with an key (primary, foreign) needs an index. 具有键(主键,外键)的每列都需要索引。 Same with column being unique. 列与唯一相同。 You probably created two indexes (one when creating FK and one on Unique constraint). 您可能创建了两个索引(一个在创建FK时,另一个在Unique约束上)。 If this is the case just drop one of those indexes. 如果是这种情况,只需删除其中一个索引。

It is overhead for the DB to maintain two equivalent indexes. DB维护两个等效索引的开销。

mysql > create unique index index_bar_id on foos(bar_id);
mysql > alter table foos add constraint index_bar_id foreign key (bar_id) references bars (id);

Read more at http://sixarm.com/about/mysql-create-indexes-foreign-keys-constraints.html 阅读更多信息,请访问http://sixarm.com/about/mysql-create-indexes-foreign-keys-constraints.html

For the future, if you want to make your foreign key unique, you can simply modify your foreign key column like this: 对于将来,如果要使外键唯一,则可以简单地修改外键列,如下所示:

ALTER TABLE your_table
MODIFY COLUMN your_fk_column [INT, VARCHAR etc.][NOT NULL] UNIQUE;

Just so you know, it seems like you can also have UNIQUE foreign keys: 您知道,似乎您也可以使用UNIQUE外键:

CREATE TABLE user(
uid INT NOT NULL AUTO_INCREMENT,
username VARCHAR(16) NOT NULL UNIQUE,
email_id INT NOT NULL UNIQUE,
FOREIGN KEY (email_id) REFERENCES email(uid)
    ON DELETE CASCADE
    ON UPDATE CASCADE,

PRIMARY KEY (uid));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM