MySQL - Unique foreign key

后端 未结 4 1752
走了就别回头了
走了就别回头了 2021-01-05 03:27

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 an         


        
相关标签:
4条回答
  • 2021-01-05 03:50

    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;
    
    0 讨论(0)
  • 2021-01-05 03:53

    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.

    0 讨论(0)
  • 2021-01-05 03:53

    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));
    
    0 讨论(0)
  • 2021-01-05 03:56
    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

    0 讨论(0)
提交回复
热议问题