Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I add a foreign key pointing to the same table using phpMyAdmin?

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...?

like image 379
AFG Avatar asked Mar 23 '09 20:03

AFG


People also ask

How do I add a foreign key to an existing table in phpMyAdmin?

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').

How do I add a foreign key to an existing table?

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,...);

Can we create foreign key on same table?

If you mean "can foreign key 'refer' to a primary key in the same table?", the answer is a firm yes as some replied.

Can I add a foreign key constraint to an existing table with data?

Of course you can add a foreign key when there is data... assuming you don't have any values that violate the new constraint.


1 Answers

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.

like image 150
Powerlord Avatar answered Sep 18 '22 17:09

Powerlord