If you are adding a foreign key and faced this error, it could be the value in the child table is not present in the parent table.
Let's say for the column to which the foreign key has to be added has all values set to 0 and the value is not available in the table you are referencing it.
You can set some value which is present in the parent table and then adding foreign key worked for me.