INNER JOIN
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 matches keys
Rows from two tables combine where the key matches.
Сложность 3/5 · 200 монет + небольшой бонус за первое завершение сегодня
List each customer's name next to the total of each of their orders. Join customer до orders on the key, ordered by orders.id.
Нажмите Запустить, чтобы увидеть результат здесь.
Сложность 3/5 · 200 монет + небольшой бонус за первое завершение сегодня
Show the customer name and order total for orders of 25 or more, largest total first.
Нажмите Запустить, чтобы увидеть результат здесь.
Сложность 3/5 · 200 монет + небольшой бонус за первое завершение сегодня
List the order id and the customer name for every order placed in March 2024 (order_date между '2024-03-01' и '2024-03-31'), ordered by order id.
Нажмите Запустить, чтобы увидеть результат здесь.