MySQL - Unique foreign key

2019-02-17 11:11发布

I have to make one of the foreign keys unique. The problem is, I am getting the following message from the 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?

4条回答
贼婆χ
2楼-- · 2019-02-17 11:13

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). If this is the case just drop one of those indexes.

It is overhead for the DB to maintain two equivalent indexes.

查看更多
Rolldiameter
3楼-- · 2019-02-17 11:13

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;
查看更多
Evening l夕情丶
4楼-- · 2019-02-17 11:39
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

查看更多
唯我独甜
5楼-- · 2019-02-17 11:39

Just so you know, it seems like you can also have UNIQUE foreign keys:

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));
查看更多
登录 后发表回答