[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); 
相关文章
相关标签/搜索