Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.Start your free trial
Priscilla Kam1,086 Points
mysql - foreign key
what is foreign key in mysql and cascade delete in mysql, and how to use it , does anyone have any example code? Thank you.
Mike Healy2,451 Points
When you have a one-to-many relationship in your data the parent row in one table might be linked to its children in another table. For example customers -> orders. A given customer might have made any number of orders.
So the customers table might have an
The orders table would have a
customer_id field which matches the records to the parent.
A foreign key means MySQL is aware of the relationship and orders.customer_id is a foreign key to customers.id
Cascade delete is option that means if the parent row is deleted (the customer) all the related records in the orders table would be deleted too (to prevent orphaned rows).
You could build this logic into your application, but it's usually better and more reliable to have the DB handle it where possible. I'm rusty on the syntax sorry.