I have an existing InnoDB table which already has foreign keys pointing to different tables.
But when I try to create a foreign key pointing to the Primary index, I get an error (check data type).
The table is User with User_Id as the Primary.
I want a foreign key Manager_ID which is a FK to User_Id.
Both of INT Both of Length 10 Unsigned...
But I still get a data check error...?
Define foreign key in phpMyAdminAfter clicking the 'Relation view' in the 'product_category' table, you can set foreign keys. You will be given a table where each row corresponds to an indexed column in your referring table ('product_category').
You can add foreign key constraint using CREATE TABLE or ALTER TABLE statements in SQL. Here's the syntax to create foreign key in MySQL. ALTER TABLE table_name ADD CONSTRAINT constraint_name FOREIGN KEY (foreign_key_name,...) REFERENCES parent_table(column_name,...);
If you mean "can foreign key 'refer' to a primary key in the same table?", the answer is a firm yes as some replied.
Of course you can add a foreign key when there is data... assuming you don't have any values that violate the new constraint.
Make sure that Manager_ID is not set to NOT NULL
.
You have to allow nulls on that field, as the top-most person in the company will have no manager.
I found a post over on the MySQL boards that might help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With