Do i need to setting the foreign key for this situation ? i'm weak in database design, especially in mysql.. may i know if i want to setting foreign keys f开发者_如何转开发or them, what should i setting for them ? in case if the people delete... all referral to people_id will delete together, is it possible to set while the table is too many ? Thx for reply
Yes. Foreign key constraints enforce referential integrity, a key tenet of ensuring that your data is reliable and of high quality. Otherwise, your people_address table could reference a people_id value that doesn't exist in the people table, and would be an orphan. A foreign key constraint would prevent that from happening.
So, just do it. There's really no good reason not to.
Define foreign keys such as the following on the people_email table:
ALTER TABLE people_email ADD CONSTRAINT FOREIGN KEY (people_id) REFERENCES people (id) ON DELETE CASCADE;
This will mean that you cannot enter a record in people_email where the people_id in that table does not exist in people. Also, if you delete the parent row in people, the rows referencing it in people_email with get automatically deleted.
I personally prefer to manually delete all the rows from the child tables and not use cascade deletes though. It's a bit of extra app dev work, but it makes me feel safer and also allows me some control over locking and ensuring that queries are as efficient as possible.
精彩评论