Tables, keys and relationships · Bảng, khóa và mối quan hệ
More than one table
Real databases split data across several tables. This lesson uses a small shop with two of them:
customer— one row per customer (id,name,city)orders— one row per order (id,customer_id,order_date,total)
Storing the customer's name on every order would repeat it again and again. Keeping customers in their own table stores each one once.
Nhiều hơn một bảng
Cơ sở dữ liệu thực tế chia sẻ dữ liệu trên nhiều bảng. Bài học này sử dụng một cửa hàng nhỏ với hai bảng:
customer— một dòng cho mỗi khách hàng (id,name,city)orders— một dòng cho mỗi đơn hàng (id,customer_id,order_date,total)
Lưu tên khách hàng trong mỗi đơn hàng sẽ khiến nó bị lặp đi lặp lại. Giữ khách hàng trong bảng riêng lưu mỗi người một lần duy nhất.
Primary keys
A primary key is the column that uniquely identifies each row. It is never blank and never repeated.
customer.idis the primary key ofcustomer.orders.idis the primary key oforders.
Given a primary key value, you can always find exactly one row.
Khóa chính
Một khóa chính là cột xác định duy nhất mỗi dòng. Nó không bao giờ trống và không bao giờ lặp lại.
customer.idlà khóa chính củacustomer.orders.idlà khóa chính củaorders.
Cho một giá trị khóa chính, bạn luôn có thể tìm thấy đúng một dòng.
Foreign keys
A foreign key is a column that holds the primary key of another table, linking the two.
orders.customer_id holds a value from customer.id — it says which customer each order belongs to.
Referential integrity means every foreign-key value must match a real primary key: an order can't belong to a customer who doesn't exist.
Khóa ngoại
Một khóa ngoại là cột chứa khóa chính của bảng khác, liên kết hai bảng với nhau.
orders.customer_id chứa một giá trị từ customer.id — nó chỉ ra khách hàng nào thuộc về mỗi đơn hàng.
Toàn vẹn tham chiếu có nghĩa là mọi giá trị khóa ngoại phải khớp với một khóa chính thực tế: một đơn hàng không thể thuộc về một khách hàng không tồn tại.
Common mistakes
- A PRIMARY KEY is unique and cannot be NULL.
- A foreign key points to another table's primary key.
Những lỗi thường gặp
- Một PRIMARY KEY là duy nhất và không thể NULL.
- Một khóa ngoại trỏ đến khóa chính của bảng khác.
Keys link two tables · Khóa liên kết hai bảng
A shared key lets a row in one table point to a row in another. · Một khóa chung cho phép một hàng trong bảng này trỏ đến một hàng trong bảng khác.
Show the whole customer table so you can see the rows and their primary key id. · Hiển thị toàn bộ bảng customer để bạn có thể thấy các hàng và khóa chính của chúng là id.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
Show each order's id, its customer_id (the foreign key), and its total, ordered by id. · Hiển thị id của từng đơn hàng, khóa ngoại customer_id của nó, và total tương ứng, sắp xếp theo id.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.