Skip to content
Advertisement

i am trying to create foreign keys but i got error 1822 .. please see my code below

Advertisement

Answer

What is this meant to do?:

It’s not uncommon for a table to have a foreign key back to its own primary key, such as for records which have a parent/child relationship. But that doesn’t seem to be the case here.

More to the point of the error though, this isn’t referencing the entire primary key for the target table. That key has two fields:

So the DBMS can’t create the foreign key because its structure doesn’t match the target primary key.

If you want to create that foreign key, it would need to match. Probably something like this:

But it doesn’t appear that you need that foreign key at all, because it doesn’t seem to make sense in your data model. Instead I suspect orderid might need to be autoincrement and just use the productid foreign key. Something like this:

(Note that there could be more changes you’d want to make to your data model. This answer doesn’t purport to provide you with a complete production-ready data model, just to correct the error. Your data model is likely to change/evolve as you develop your system.)

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement