开发者

Foreign key in mysql table- is the presence of target data necessary?

I have 2 tables

TableA(id_A, name_A, info_A)

tableB(id_B, A_id, some_data) foreign key(A_id) references tableA(id_A)

So when I insert a row in B, with value XXX as value in the second column id_A, is it necessary that the table_A should have a row with XXX as id?

If not, then what constraint should i lay upon the tables so that table B references on开发者_如何学Cly a table_A row that is present?


Yes, if TableA.id_A is the primary key, and TableB.A_id has a foreign key constraint referencing that primary key, then the XXX value must exist in TableA.id_A before TableB.A_id can contain XXX.

It also means you can't delete or change the XXX value in TableA.id_A while the value XXX exists in TableB.A_id. You would have to delete, change, or set NULL the value in TableB.A_id first. You could also declare the foreign key with CASCADE options so that changes in TableA are also applied to TableB atomically. But you can never have an "orphan" value in a dependent table.

Note that if you use the MyISAM storage engine for either TableA or TableB, then your definition of a foreign key constraints is silently ignored, and the database doesn't enforce any referential integrity between the two tables. You must use the InnoDB storage engine for both tables to get support for foreign key constraints.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜