SQL JOIN語法 產品銷售分析 I Leetcode #1068

2024/01/01閱讀時間約 7 分鐘

題目敘述

題目會給我們兩張資料表,第一張是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

43會員
286內容數
由有業界實戰經驗的演算法工程師, 手把手教你建立解題的框架, 一步步寫出高效、清晰易懂的解題答案。 著重在讓讀者啟發思考、理解演算法,熟悉常見的演算法模板。 深入淺出地介紹題目背後所使用的演算法意義,融會貫通演算法與資料結構的應用。 在幾個經典的題目融入一道題目的多種解法,或者同一招解不同的題目,擴展廣度,並加深印象。
留言0
查看全部
發表第一個留言支持創作者!