Skip to content
Advertisement

MySQL Error – Cannot add foreign key constraint

I know this question has been asked several times but it seemed like the problem was due to different data types between parent and child rows. In my case, the data types are the same but I’m still getting the error. Here’s my code

Where DORM_COSTS’ foreign key cannot be added. Thanks!

Advertisement

Answer

You want the foreign key reference on the table that has the foreign key, not the primary key. So, that would be:

Here is a db<>fiddle that shows that this works.

That said your data model seems quite strange.

  • I would expect a table called RoomTypes to have a primary key of RoomTypeId.
  • I would expect dorm_cost to have dates, because costs can vary from year to year.
  • I would expect different dorms to have similar room types — singles, doubles, and so on.
  • I would expect those room types to vary, perhaps, by dorm.
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement