SQL JOIN語法 用UID取代員工ID Leetcode #1378

2023/12/29閱讀時間約 3 分鐘

題目敘述

題目會給我們兩張資料表。

第一張資料表是Employees

裡面分別有id、name等欄位。這張資料表的id是主鍵


第二張資料表是EmployeeUNI

裡面分別有id、unique_id等欄位。這張資料表的(id、unique_id)是複合主鍵id。


題目要求我們列出每位員工所對應到的unique_id,如果對應不到,則填上null


Table: Employees

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| name | varchar |
+---------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table contains the id and the name of an employee in a company.

Table: EmployeeUNI

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| unique_id | int |
+---------------+---------+
(id, unique_id) is the primary key (combination of columns with unique values) for this table.
Each row of this table contains the id and the corresponding unique id of an employee in the company.

詳細的題目可在這裡看到


約束條件

列出每位員工所對應到的unique_id,如果對應不到,則填上null


演算法

Employees 和 ​EmployeeUNI 做 LEFT JOIN ​

連接的條件為 e.id = e_uni.id

假如第一次接觸SQL或者JOIN語法的同學,可參考 LEFT JOIN 語法教學


程式碼

SELECT e_uni.unique_id, e.name
FROM Employees e LEFT JOIN EmployeeUNI e_uni
ON e.id = e_uni.id;

Reference:

[1] MySQL by LEFT JOIN - Replace Employee ID With The Unique Identifier - LeetCode

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