[LeetCode#175]Combine Two Tables

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

  

本題是比較簡單的題目:要求讓咱們寫一個SQL查詢,報表能爲person表中的每一個人提供FirstName、LastName、City、和State,不管這些人是否有地址:sql

 解法一:less

SELECT a.FirstName, a.LastName,  b.City, b.State FROM Person as a 
LEFT JOIN Address as b 
on a.PersonId = b.PersonId;

  

解法二:ide

  可使用關鍵字NATURAL,這樣咱們就不要申明具體的列了,MySQL能夠自行搜搜相同的列:this

SELECT a.FirstName, a.LastName, b.City, b.State 
FROM Person as a 
NATURAL LEFT JOIN  Address as b; 

  

解法三:
  在使用LEFT JOIN時,咱們也可使用關鍵字USING來申明咱們想用哪一個列名來進行聯合:spa

SELECT a.FirstName, a.LastName, b.City, b.State 
FROM Person as a 
LEFT JOIN  Address as b
USING(PersonId); 
相關文章
相關標籤/搜索