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.
การเชื่อมสองตาราง
เพื่อใช้ข้อมูลจาก ทั้งสอง ตารางพร้อมกัน คุณต้อง เชื่อมต่อ它们 An 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.
เฉพาะแถวที่ตรงกันเท่านั้นที่คงอยู่
An INNER JOIN รักษาแถว ก็ต่อเมื่อ ON เงื่อนไขพบการจับคู่ในตารางอื่นเท่านั้น
ในร้านของเรา Ben และ Dan ไม่มีคำสั่งซื้อ所以他们 ไม่ปรากฏ ในการเชื่อมต่อ — ไม่มีอะไรให้จับคู่กับพวกเขา Ada และ Cara ซึ่งมีคำสั่งซื้อ ปรากฏหนึ่งครั้งสำหรับแต่ละคำสั่งซื้อของพวกเขา
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.
ข้อผิดพลาดทั่วไป
- Match บน key ด้วย
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. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
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. · คลิก Run เพื่อดูผลลัพธ์ที่นี่