SQL實(shí)現(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ù)庫的題,來那么也來做做吧,這道題是第一道,相對(duì)來說比較簡(jiǎn)單,是一道兩表聯(lián)合查找的問題,我們需要用到Join操作,關(guān)于一些Join操作可以看我之前的博客SQL Left Join, Right Join, Inner Join, and Natural Join 各種Join小結(jié),最直接的方法就是用Left Join來做,根據(jù)PersonId這項(xiàng)來把兩個(gè)表聯(lián)合起來:
解法一:
SELECT Person.FirstName, Person.LastName, Address.City, Address.State FROM Person LEFT JOIN Address ON Person.PersonId = Address.PersonId;
在使用Left Join時(shí),我們也可以使用關(guān)鍵Using來聲明我們相用哪個(gè)列名來進(jìn)行聯(lián)合:
解法二:
SELECT Person.FirstName, Person.LastName, Address.City, Address.State FROM Person LEFT JOIN Address USING(PersonId);
或者我們可以加上Natural關(guān)鍵字,這樣我們就不用聲明具體的列,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
到此這篇關(guān)于SQL實(shí)現(xiàn)LeetCode(175.聯(lián)合兩表)的文章就介紹到這了,更多相關(guān)SQL實(shí)現(xiàn)聯(lián)合兩表內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信