SQL實現(xiàn)LeetCode(175.聯(lián)合兩表)
[LeetCode] 175.Combine Two Tables 聯(lián)合兩表
Table: Person
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| PersonId | int |
| FirstName | varchar |
| LastName | varchar |
+-------------+---------+
PersonId is the primary key column for this table.
Table: Address
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| AddressId | int |
| PersonId | int |
| City | varchar |
| State | varchar |
+-------------+---------+
AddressId is the primary key column for this table.
Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people:
FirstName, LastName, City, State
LeetCode還出了是來到數(shù)據(jù)庫的題,來那么也來做做吧,這道題是第一道,相對來說比較簡單,是一道兩表聯(lián)合查找的問題,我們需要用到Join操作,關于一些Join操作可以看我之前的博客SQL Left Join, Right Join, Inner Join, and Natural Join 各種Join小結,最直接的方法就是用Left Join來做,根據(jù)PersonId這項來把兩個表聯(lián)合起來:
解法一:
SELECT Person.FirstName, Person.LastName, Address.City, Address.State FROM Person LEFT JOIN Address ON Person.PersonId = Address.PersonId;
在使用Left Join時,我們也可以使用關鍵Using來聲明我們相用哪個列名來進行聯(lián)合:
解法二:
SELECT Person.FirstName, Person.LastName, Address.City, Address.State FROM Person LEFT JOIN Address USING(PersonId);
或者我們可以加上Natural關鍵字,這樣我們就不用聲明具體的列,MySQL可以自行搜索相同的列:
解法三:
SELECT Person.FirstName, Person.LastName, Address.City, Address.State FROM Person NATURAL LEFT JOIN Address;
參考資料:
https://leetcode.com/discuss/21216/its-a-simple-question-of-left-join-my-solution-attached
https://leetcode.com/discuss/53001/comparative-solution-between-left-using-natural-left-join
到此這篇關于SQL實現(xiàn)LeetCode(175.聯(lián)合兩表)的文章就介紹到這了,更多相關SQL實現(xiàn)聯(lián)合兩表內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
MySQL學習第五天 MySQL數(shù)據(jù)庫基本操作
MySQL學習第五天我們將針對MySQL數(shù)據(jù)庫進行基本操作,創(chuàng)建、修改、刪除數(shù)據(jù)庫等一系列操作進行學習,感興趣的小伙伴們可以參考一下2016-05-05
解析MySQL創(chuàng)建外鍵關聯(lián)錯誤 - errno:150
本篇文章是對MySQL創(chuàng)建外鍵關聯(lián)錯誤-errno:150進行了詳細的分析介紹,需要的朋友參考下2013-06-06
Windows下通過cmd進入DOS窗口訪問MySQL數(shù)據(jù)庫
這篇文章主要介紹了Windows下通過cmd進入DOS窗口訪問MySQL數(shù)據(jù)庫的實現(xiàn)方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03
mysql報錯RSA?private?key?file?not?found的解決方法
當MySQL報錯RSA?private?key?file?not?found時,可能是由于MySQL的RSA私鑰文件丟失或者損壞導致的,此時可以重新生成RSA私鑰文件,以解決這個問題2023-06-06
深入淺析MySQL 中 Identifier Case Sensitivity問題
這篇文章主要介紹了MySQL 中 Identifier Case Sensitivity,需要的朋友可以參考下2018-09-09
Canal進行MySQL到MySQL數(shù)據(jù)庫全量+增量同步踩坑指南
這篇文章主要介紹了使用Canal作為遷移工具,將數(shù)據(jù)庫從A服務器遷移至B服務器,為了盡量減少遷移導致的停機時間,考慮使用全量遷移+增量同步的方式2023-10-10

