The documentation to which you refer is correct, but not clear enough.
Suppose you had a table of employees. You want each row to have a column manager_id
which is a foreign key referencing another row which is the employee's manager. But for some reason, you don't use employee_id as the primary key of the table -- you have another primary key.
mysql> create table employees (
id serial primary key,
employee_id int,
manager_id int
);
You would like to add a foreign key on manager_id
, referencing employee_id
:
mysql> alter table employees add foreign key (manager_id) references employees(employee_id);
ERROR 1215 (HY000): Cannot add foreign key constraint
What's wrong? There's no index on employee_id
but a foreign key can only reference a column with an index. This is a little more clear if we get the detail about the foreign key error in the innodb status:
mysql> show engine innodb status\G
...
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2019-12-26 10:25:52 0x700005bfb000 Error in foreign key constraint of table test/#sql-159d_8c9:
foreign key (manager_id) references employees(employee_id):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns...
...
You need to create an index on employee_id
first:
mysql> alter table employees add unique key (employee_id);
Query OK, 0 rows affected (0.01 sec)
mysql> alter table employees add foreign key (manager_id) references employees(employee_id);
Query OK, 0 rows affected (0.02 sec)
So the documentation was correct to say "remember to create the required indexes first," but it was not clear that the required index is on the referenced column (employee_id). You assumed the documentation was talking about a required index on the foreign key column (manager_id).
In fact, creating the foreign key will automatically create the index on the foreign key column, unless an index on that column already exists.