Can the same column have primary key & foreign key constraint to another column?
Table1: ID - Primary column, foreign key constraint for Table2 ID
Table2: ID - Primary column, Name
Will this be an issue if i try to delete table1 data?
Delete from table1 where ID=1000;
Thanks.
Yes, it can.
No, it won't.
P.S. But you'll not be able to delete table2 data without deleting corresponding table1 rows obviously.
P.P.S. I've implemented such structure in Postgres, but it must be similar for MySQL.
There should be no problem with that. Consider the following example:
The tables now contain:
Now we can successfully delete rows like this:
However we won't be able to delete the following:
If we had defined the foreign key on
table1
with theCASCADE
option, we would have been able to delete the parent, and all the children would get deleted automatically:If we were to repeat the previously failed
DELETE
, the children rows intable1
will be deleted as well as the parent row intable2
:Assigning Primary Key And Foreign key to the same column in a Table: