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הוא המפתח הראשי שלcustomer.orders.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 מכיל ערך ממ_chart 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. · לחץ על הרץ כדי לראות את התוצא כאן.
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. · לחץ על הרץ כדי לראות את התוצא כאן.