iT邦幫忙

0

leetcode with MySQL:175. Combine Two Tables

  • 分享至 

  • xImage
  •  

刷leetcode遇到SQL的題目,那也只能換個語言了

題目:

Table: Person

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| personId | int |
| lastName | varchar |
| firstName | varchar |
+-------------+---------+
personId is the primary key column for this table.
This table contains information about the ID of some persons and their first and last names.

Table: Address

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| addressId | int |
| personId | int |
| city | varchar |
| state | varchar |
+-------------+---------+
addressId is the primary key column for this table.
Each row of this table contains information about the city and state of one person with ID = PersonId.

Write an SQL query to report the first name, last name, city, and state of each person in the Person table. If the address of a personId is not present in the Address table, report null instead.

Return the result table in any order.

給定兩個table,結合兩者
report People table裡所有人的first name,last name,city,state(兩table personId是對應的)
若該personId在Address沒有資料,city,state格就填NULL

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

將兩個table結合,條件訂personId相等
記得用left join這樣在Address沒對應資料的人city,state才會填NULL
之後將firstName,lastName,city,state選出就好
最後執行時間320ms(faster than 95.44%)

那我們下題見


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言