175. Combine Two Tables
题目描述和难度
- 题目描述:
表1: Person
+-------------+---------+ | 列名 | 类型 | +-------------+---------+ | PersonId | int | | FirstName | varchar | | LastName | varchar | +-------------+---------+ PersonId 是上表主键
表2: Address
+-------------+---------+ | 列名 | 类型 | +-------------+---------+ | AddressId | int | | PersonId | int | | City | varchar | | State | varchar | +-------------+---------+ AddressId 是上表主键
编写一个 SQL 查询,满足条件:无论 person 是否有地址信息,都需要基于上述两表提供 person 的以下信息:
FirstName, LastName, City, State
- 题目难度:简单。
- 英文网址:175. Combine Two Tables 。
- 中文网址:175. 组合两个表 。
思路分析
求解关键:其实就考了左连接。
用于测试的 SQL 语句:
DROP TABLE IF EXISTS Person;
DROP TABLE IF EXISTS Address;
CREATE TABLE Person(
PersonId INT PRIMARY KEY AUTO_INCREMENT,
FirstName VARCHAR(200),
LastName VARCHAR(200)
);
insert into Person(FirstName,LastName) values('li','wei');
insert into Person(FirstName,LastName) values('zhou','guang');
insert into Person(FirstName,LastName) values('yuan','lian');
CREATE TABLE Address(
AddressId INT PRIMARY KEY AUTO_INCREMENT,
PersonId INT,
City VARCHAR(200),
State VARCHAR(200)
);
insert into Address(PersonId,City,State) values(1,'beijng','haidianqu');
insert into Address(PersonId,City,State) values(2,'shanghai','xuhuiqu');
参考解答
参考解答1
select t1.FirstName, t1.LastName, t2.City, t2.State
from Person t1 left join Address t2 on t1.`PersonId` = t2.`PersonId`;
本篇文章的地址为 https://liweiwei1419.github.io/leetcode-solution/leetcode-0175-combine-two-tables ,如果我的题解有错误,或者您有更好的解法,欢迎您告诉我 liweiwei1419@gmail.com 。