題目會給我們兩張資料表,第一張是Sales,第二張是Product。
第一張是Sales表格,裡面分別有sale_id、 product_id、year、quantity、price等欄位。其中(sale_id、 product_id)做為複合主鍵Primary key
Table: Sales
+-------------+-------+
| Column Name | Type |
+-------------+-------+
| sale_id | int |
| product_id | int |
| year | int |
| quantity | int |
| price | int |
+-------------+-------+
(sale_id, year) is the primary key (combination of columns with unique values) of this table.
product_id is a foreign key (reference column) to Product table.
Each row of this table shows a sale on the product product_id in a certain year.
Note that the price is per unit.
第二張是Product表格,裡面分別有product_id 、 product_name 等欄位。其中 product_id做為主鍵Primary key
Table: Product
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| product_id | int |
| product_name | varchar |
+--------------+---------+
product_id is the primary key (column with unique values) of this table.
Each row of this table indicates the product name of each product.
要求我們列出每一項銷售產品的 產品名稱product_name、銷售年分year、銷售價格price
輸出的順序不拘。
Example 1:
Input:
Sales table:
+---------+------------+------+----------+-------+
| sale_id | product_id | year | quantity | price |
+---------+------------+------+----------+-------+
| 1 | 100 | 2008 | 10 | 5000 |
| 2 | 100 | 2009 | 12 | 5000 |
| 7 | 200 | 2011 | 15 | 9000 |
+---------+------------+------+----------+-------+
Product table:
+------------+--------------+
| product_id | product_name |
+------------+--------------+
| 100 | Nokia |
| 200 | Apple |
| 300 | Samsung |
+------------+--------------+
Output:
+--------------+-------+-------+
| product_name | year | price |
+--------------+-------+-------+
| Nokia | 2008 | 5000 |
| Nokia | 2009 | 5000 |
| Apple | 2011 | 9000 |
+--------------+-------+-------+
Explanation:
From sale_id = 1, we can conclude that Nokia was sold for 5000 in the year 2008.
From sale_id = 2, we can conclude that Nokia was sold for 5000 in the year 2009.
From sale_id = 7, we can conclude that Apple was sold for 9000 in the year 2011.
考點主要在考怎麼串聯兩張表格? 用兩張表格共有的product_id欄位做連接,並且依照提議印出產品名稱product_name、銷售年分year、銷售價格price。
對應的SQL語法
SELECT ...欄位
FROM ...第一張表格
JOIN ...第二張表格 USING(共同欄位)
或者
SELECT ...欄位
FROM ...第一張表格
JOIN ...第二張表格
ON ...連接條件
SELECT P.product_name, S.year, S.price
FROM Sales S
LEFT JOIN Product P USING(product_id);
SELECT P.product_name, S.year, S.price
FROM Sales S
LEFT JOIN Product P
ON P.product_id=S.product_id;
掌握JOIN 的SQL語法 搭配連接條件判斷的用法
SELECT ...欄位
FROM ...第一張表格
JOIN ...第二張表格 USING(共同欄位)
或者
SELECT ...欄位
FROM ...第一張表格
JOIN ...第二張表格
ON ...連接條件
Reference:
[1] MySQL by LEFT JOIN ... USING(common key) - Product Sales Analysis I - LeetCode