A combination of the two tables
Table 1: Person
+ ------------- + --------- +
| Column Name | Type |
+ ------------- + ---- + -----
| PersonId | int |
| FirstName | VARCHAR |
| LastName | VARCHAR |
+ ------------- + --------- +
PersonId is on the table primary key
table 2: Address
+ ------------- + --------- +
| Column Name | Type |
+ ------------- + ---- + -----
| AddressID | int |
| PersonId | int |
| City | VARCHAR |
| State | VARCHAR |
+ ------------- + --------- +
AddressID table is a primary key
Write a SQL query, the condition: no matter whether the person has address information, we need to provide the following information based on the person of two tables:
Construction of the table statement:
Create table Person (PersonId int, FirstName varchar(255), LastName varchar(255)) Create table Address (AddressId int, PersonId int, City varchar(255), State varchar(255)) Truncate table Person insert into Person (PersonId, LastName, FirstName) values ('1', 'Wang', 'Allen') Truncate table Address insert into Address (AddressId, PersonId, City, State) values ('1', '2', 'New York City', 'New York')
solution:
select FirstName, LastName, City, State from Person left join Address on Person.PersonId = Address.PersonId
FirstName, LastName, City, State
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/combine-two-tables
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.