0
votes

I've created a table for accounts/users with a primary key (UsersID, AccountsID) like below. Should I add the index for the Users table?

create table AccountsUsers
(
    AccountsID int unsigned not null,
    UsersID int unsigned not null,
    Roles bigint unsigned null,
    primary key (UsersID, AccountsID),
    constraint AccountsUsers_Accounts_ID_fk
        foreign key (AccountsID) references Accounts (ID)
            on update cascade on delete cascade,
    constraint AccountsUsers_Users_ID_fk
        foreign key (UsersID) references Users (ID)
            on update cascade on delete cascade
)
engine=InnoDB
;

create index AccountsUsers_Accounts_ID_fk
    on AccountsUsers (AccountsID)
;
2

2 Answers

0
votes

From the documentation

MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.

In other words, if you don't already have the required indexes on the columns of your referencing table (AccountsUsers), MySQL will create them for you.

If the columns in the referenced tables (Accounts and Users) are not indexed you will get an error. Your's look like they will be Primary Keys on their respective tables, so you should be fine.

0
votes

MySQL will create the necessary indexes for the foreign key automatically, if necessary.

In the case of your foreign key on UsersId, it can use the left column of your primary key. It doesn't need to create a new index for that foreign key.

In the case of your foreign key on AccountsId, MySQL will create a new index automatically. It can't use the fact that AccountsId is part of your primary key, because it isn't the left-most column.

After you do the CREATE TABLE, run SHOW CREATE TABLE AccountsUsers and you should see the new index it created for AccountsId.