王廷瑋|數位醫療|智慧醫療: 175. Combine Two Tables WFU

2024年7月9日 星期二

175. Combine Two Tables

175. Combine Two Tables


表格:Person

+-------------+---------+ 
| 列名 | 類型 | 
+-------------+---------+ 
| personId | int |
| lastName | varchar | 
| firstName | varchar | 
+-------------+---------+ 
personId 是此表格的主鍵(具有唯一值的列)。 此表包含某些人的 ID 及其名字和姓氏的信息。

表格:Address

+-------------+---------+ 
| 列名 | 類型 | 
+-------------+---------+ 
| addressId | int | 
| personId | int | 
| city | varchar | 
| state | varchar | 
+-------------+---------+ 
addressId 是此表格的主鍵(具有唯一值的列)。 此表的每一行包含一個 ID 為 personId 的人的城市和州的信息。

撰寫一個解決方案來報告 Person 表中每個人的名字、姓氏、城市和州。如果在 Address 表中沒有該 personId 的地址,則報告 null。

以任何順序返回結果表。

結果格式如下例所示。

範例:

輸入: Person 表:
 +----------+----------+-----------+ 
| personId | lastName | firstName | 
+----------+----------+-----------+ 
| 1 | Wang | Allen | | 2 | Alice | Bob | 
+----------+----------+-----------+ 
Address 表: 
+-----------+----------+---------------+------------+
 | addressId | personId | city | state | 
+-----------+----------+---------------+------------+
 | 1 | 2 | New York City | New York | 
| 2 | 3 | Leetcode | California | 
+-----------+----------+---------------+------------+

輸出: 
+-----------+----------+---------------+----------+ 
| firstName | lastName | city | state | 
+-----------+----------+---------------+----------+ 
| Allen | Wang | Null | Null |
 | Bob | Alice | New York City | New York | 
+-----------+----------+---------------+----------+

解釋: 對於 personId = 1,Address 表中沒有對應的地址,因此在 city 和 state 列中返回 null。 addressId = 1 包含 personId = 2 的地址信息。


MySQL


# Write your MySQL query statement below

SELECT p.firstName, p.lastName, a.city, a.state
FROM Person p
LEFT JOIN Address a ON p.personId = a.personId;

1169ms


Pandas


import pandas as pd

def combine_two_tables(person: pd.DataFrame, address: pd.DataFrame) -> pd.DataFrame:
# Perform a left join on person and address DataFrames
result = pd.merge(person, address, how='left', left_on='personId', right_on='personId')
# Select the desired columns and rename them if necessary
result = result[['firstName', 'lastName', 'city', 'state']]
return result

67.46MB, 388ms


PostgreSQL


-- Write your PostgreSQL query statement below

SELECT p.firstName, p.lastName, a.city, a.state
FROM Person p
LEFT JOIN Address a ON p.personId = a.personId;

0.00MB, 297ms