Tables, keys and relationships · ตาราง คีย์ และความเชื่อมโยง
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.
أكثرจากหนึ่งตาราง
ฐานข้อมูลจริงแยกข้อมูลออกใน หลายตาราง บทเรียนนี้ใช้ร้านเล็กๆ ที่มีสองตาราง:
customer— แถวละหนึ่งแถวสำหรับลูกค้า (id,name,city)orders— แถวละหนึ่งแถวสำหรับคำสั่งซื้อ (id,customer_id,order_date,total)
การเก็บชื่อลูกค้าไว้ในคำสั่งซื้อทุกฉบับจะทำให้ซ้ำซ้อน การรักษาข้อมูลลูกค้าในตารางแยกต่างหากจะเก็บแต่ละคนไว้ หนึ่งครั้ง เท่านั้น
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.
คีย์หลัก
คีย์หลัก คือคอลัมน์ที่ ระบุตัวตน每条แถวได้อย่าง ไม่ซ้ำ มันจะไม่ว่างเปล่าและไม่ซ้ำ
customer.idเป็นคีย์หลักของcustomerorders.idเป็นคีย์หลักของorders
เมื่อทราบค่าคีย์หลัก คุณสามารถหาแถวที่ตรงกันได้อย่างถูกต้องหนึ่งแถวเสมอ
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.
คีย์ภายนอก
คีย์ภายนอก คือคอลัมน์ที่เก็บคีย์หลักของ ตารางอื่น เพื่อเชื่อมโยงสองตารางเข้าด้วยกัน
orders.customer_id เก็บค่าจาก customer.id — ซึ่งบอกรายละเอียดว่า ลูกค้ารายใด คำสั่งซื้อนั้นเป็นของเขา
ความสมบูรณ์ของการอ้างอิง หมายความว่าค่าคีย์ภายนอกทุกค่าต้องตรงกับคีย์หลักที่มีอยู่จริง: คำสั่งซื้อไม่สามารถเป็นของลูกค้าที่ไม่มีอยู่จริงได้
Common mistakes
- A PRIMARY KEY is unique and cannot be NULL.
- A foreign key points to another table's primary key.
ข้อผิดพลาดทั่วไป
- PRIMARY KEY มีความไม่ซ้ำและไม่เป็น NULL ได้
- คีย์ภายนอกชี้ไปที่คีย์หลักของตารางอื่น
Keys link two tables · คีย์เชื่อมสองตารางเข้าด้วยกัน
A shared key lets a row in one table point to a row in another. · คีย์ ที่ร่วมกันช่วยให้แถวในตารางหนึ่งชี้ไปยังแถวในอีกตารางหนึ่งได้
Show the whole customer table so you can see the rows and their primary key id. · แสดงทั้งตาราง customer เพื่อให้เห็นแถวและคีย์หลัก id ของมัน
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Show each order's id, its customer_id (the foreign key), and its total, ordered by id. · แสดง id ของคำสั่งซื้อแต่ละรายการ, customer_id ของมัน (คีย์ภายนอก), และ total ของมัน เรียงลำดับตาม id
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่