INNER JOIN
Joining two tables
To use data from both tables at once, you join them. An INNER JOIN pairs up rows that match on a key — here, the order's customer_id with the customer's id:
When a column name could come from either table, write table.column so it is clear.
חיבור שתי טבלאות
כדי להשתמש בנתונים מ-שתי הטבלאות בו-זמנית, יש להצמיד אותן. INNER JOIN זוגות שורות התואמות על פי מפתח — כאן, הזמנה של customer_id עם הלקוח של id:
SELECT customer.name, orders.total
FROM customer
INNER JOIN orders ON customer.id = orders.customer_id;
כששם עמודה יכול לבוא מכל טבלה, כתיבת table.column מבהירה זאת.
Only matching rows survive
An INNER JOIN keeps a row only when the ON condition finds a match in the other table.
In our shop, Ben and Dan have no orders, so they do not appear in the join — there is nothing to pair them with. Ada and Cara, who do have orders, appear once for each of their orders.
רק שורות התואמות נשארות
INNER JOIN שומר שורה רק כאשר תנאי ה-ON מוצא התאמה בטבלה השנייה.
בחנות שלנו, לבן ודן אין להם הזמנות, ולכן הם לא מופיעים בתוצאות החיבור — אין מה לתאר אותם איתו. אדה וקארה, שיש להן הזמנות, מופיעים פעם אחת עבור כל הזמנה שלהן.
Common mistakes
- Match on the key with
ON; a missingONpairs every row with every row. - INNER JOIN drops rows with no match on the other side.
טעויות נפוצות
- התאם לפי המפתח עם
ON; חוסר ה-ONמתאר כל שורה עם כל שורה. - INNER JOIN מסיר שורות שאינם מוצאים התאמה בצד השני.
INNER JOIN matches keys · INNER JOIN מתאים מפתחות
Rows from two tables combine where the key matches. · שורות משני טבלות מתמזגים כאשר המפתח תואם.
List each customer's name next to the total of each of their orders. Join customer to orders on the key, ordered by orders.id. · רשימו את הname של כל לקוח לצד הtotal של כל הזמנה שלו. חברו customer לorders לפי המפתח, ומיון לפי orders.id.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Show the customer name and order total for orders of 25 or more, largest total first. · הציגו את הname של הלקוח ואת הtotal של ההזמנה עבור הזמנות ב25 או יותר, בסדר יורד לפי סך הכל.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.