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:
SELECT customer.name, orders.total
FROM customer
INNER JOIN orders ON customer.id = orders.customer_id;
When a column name could come from either table, write table.column so it is clear.
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.
Question. The table orders stores only a customer_id. Write a query to show the name of the customer who placed order 12.
Answer. The name is in customer, the order number in orders, so join them on the key and then keep the one order:
SELECT customer.name
FROM customer
INNER JOIN orders ON customer.id = orders.customer_id
WHERE orders.id = 12;
name
Cara
The join comes first, then WHERE filters the joined rows, then ORDER BY (if any) sorts them.
- Joining on the wrong columns.
ON customer.id = orders.idcompares customer numbers (1 to 4) with order numbers (10 to 13): nothing matches, so you get no rows at all. Join the foreign key to the primary key it points to. - A column name both tables have.
SELECT id FROM customer INNER JOIN orders …fails withambiguous column name: id. Writecustomer.idororders.id. INNER JOINdrops rows with no match on the other side: Ben and Dan never appear.
INNER JOIN은 키를 매칭시킵니다
두 테이블의 행들이 키가 일치하는 지점에서 결합됩니다.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
각 고객의 name과 해당 주문들의 total 나열을 표시하십시오. 키를 기준으로 customer를 orders에 조인하고, orders.id으로 정렬하십시오.
출력을 보려면 '실행'을 클릭하세요.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
주문 총액이 25 이상인 경우의 고객 name과 주문 total을 표시하되, 가장 큰 총액부터 정렬하십시오.
출력을 보려면 '실행'을 클릭하세요.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
3월 2024 (order_date이 '2024-03-01'와 '2024-03-31' 사이)에 placed된 모든 주문의 주문 id과 고객 name을 나열하시오. 주문 id에 따라 정렬하십시오.
출력을 보려면 '실행'을 클릭하세요.