要同时使用两张表的数据,就把它们连接起来。INNER JOIN 把在某个键上匹配的行配成一对 —— 这里是订单的 customer_id 和顾客的 id:
SELECT customer.name, orders.total
FROM customer
INNER JOIN orders ON customer.id = orders.customer_id;
当一个列名两张表都可能有时,写成 table.column,这样更清楚。
INNER JOIN 只在 ON 条件能在另一张表里找到匹配时,才保留这一行。
在我们的商店里,Ben 和 Dan 没有订单,所以他们不会出现在连接结果里 —— 没有东西能和他们配对。有订单的 Ada 和 Cara,则会按其订单数各出现若干次。
问题。 表 orders 仅存储一个 customer_id。编写查询以显示下订单 12 的客户姓名。
答案。 姓名位于 customer 中,订单号位于 orders 中,因此按键连接它们,然后保留其中一个订单:
SELECT customer.name
FROM customer
INNER JOIN orders ON customer.id = orders.customer_id
WHERE orders.id = 12;
name
Cara
连接操作最先执行,然后WHERE过滤已连接的行,最后ORDER BY(如果存在)对它们进行排序。
- 在错误的列上进行连接。
ON customer.id = orders.id将客户编号(1至4)与订单编号(10至13)进行比较:没有任何匹配项,因此返回的行数为零。请将外键连接到它所指向的主键。 - 两张表共有的列名。
SELECT id FROM customer INNER JOIN orders …会因ambiguous column name: id而失败。请编写customer.id或orders.id。 INNER JOIN会丢弃另一侧没有匹配项的行:Ben和Dan永远不会出现。
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' and '2024-03-31'), ordered by order id.
点击“运行”查看此处输出。