Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a foreign key in phpmyadmin

I want to make doctorid a foreign key in my patient table.

So I have all of my tables created - the main problem is that when I go to the table > structure > relation view only the primary key comes up that I can create a foreign key (and it is already the primary key of the certain table that I want to keep - i.e Patient table patient is enabled to be changed but the doctor Id -I have a doctor table also- is not enabled).

I have another table with two composite keys (medicineid and patientid) in relation view it enables me to change both

Do I have to chance the index of doctor ID in patient table to something else? both cannot be primary keys as patient ID is the primary for the patient table - doctor is the foreign.

table

I hope anyone can help

Kind regards

like image 404
laurajs Avatar asked Jun 03 '16 13:06

laurajs


People also ask

What is a foreign key in phpMyAdmin?

A foreign key is a column or group of columns in a relational database table. It provides a link between data in two tables. For a column acting as a foreign key, a corresponding value should exist in the link table. Foreign keys and their implementation are more complex than primary keys.

How do I find my foreign key in phpMyAdmin?

To see FKs of a table first select table from the object explorer, then go to Structure tab and then select Relation view. Please note that in different versions it might be in different locations. On the Relation view screen you will see all foreign keys defined for this table (as a foreign table).

How foreign key is created?

To create a new table containing a foreign key column that references another table, use the keyword FOREIGN KEY REFERENCES at the end of the definition of that column. Follow that with the name of the referenced table and the name of the referenced column in parentheses.


1 Answers

You can do it the old fashioned way... with an SQL statement that looks something like this

ALTER TABLE table_1_name     ADD CONSTRAINT fk_foreign_key_name     FOREIGN KEY (table_1_column_name)     REFERENCES target_table(target_table_column_name)     ON DELETE action_name     ON UPDATE action_name; 

For example: If you have books table with column created_by which refere to column id in users table:

ALTER TABLE books ADD CONSTRAINT books_FK_1 FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE; 

Note: CASCADE mean if you delete from users table, related rows from books table will be deleted

This assumes the keys already exist in the relevant table

like image 139
Jon Story Avatar answered Sep 18 '22 14:09

Jon Story