@lizzie
To set up foreign keys in MySQL, follow these steps:
1 2 3 4 |
ALTER TABLE child_table ADD CONSTRAINT constraint_name FOREIGN KEY (child_column) REFERENCES parent_table(parent_column); |
For example, to set "customer_id" in the "orders" table as a foreign key referencing "customer_id" in the "customers" table, you would run the following command:
1 2 3 4 |
ALTER TABLE orders ADD CONSTRAINT fk_orders_customers FOREIGN KEY (customer_id) REFERENCES customers(customer_id); |
This statement creates a foreign key constraint named "fk_orders_customers" that references the "customer_id" column in the "customers" table.
1 2 3 4 5 |
ALTER TABLE orders ADD CONSTRAINT fk_orders_customers FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON DELETE CASCADE; |
In this example, when a customer is deleted from the "customers" table, all corresponding orders in the "orders" table will also be deleted.
Note: Before adding foreign key constraints, make sure that the referenced columns in the parent table have appropriate indexes.