Dieses Blog durchsuchen

Samstag, 16. Juli 2016

mysql: add / editing a foreign key after database was created

This task is simple but offten needed.

If you have created a databasetable and you forgot the foreignkeys, you can simply add it later via altering table.

Add a foreignkey
ALTER TABLE post
ADD FOREIGN KEY (`userid`)
REFERENCES user(`id`)
ON DELETE CASCADE
ON UPDATE CASCADE
view raw gistfile1.txt hosted with ❤ by GitHub


This key references the userid from users to a tupel in table posts. If a user gets deleted or updated the post will be deleted to0.

Deleting a foreign key
alter table post drop foreign key post_ibfk_1
view raw gistfile1.txt hosted with ❤ by GitHub

asdasd

Keine Kommentare:

Kommentar veröffentlichen