---
# System prepended metadata

title: MySQL Foreign Key
tags: [MySQL]

---

# MySQL Foreign Key

```sql=
CREATE TABLE customers(
  id INT AUTO_INCREMENT PRIMARY KEY,
  first_name VARCHAR(100),
  last_name VARCHAR(100),
  email VARCHAR(100)
);

CREATE TABLE orders(
  id INT AUTO_INCREMENT PRIMARY KEY,
  order_date DATE,
  amount DECIMAL(8,2),
  customer_id INT,
  FOREIGN KEY(customer_id) REFERENCES customers(id) ON DELETE CASCADE -- 添加外鍵，
  -- 且刪除父表(customers)資料時，若子表(orders)有對應的資料則會連帶刪除。
);
```

###### tags: `MySQL`