0
点赞
收藏
分享

微信扫一扫

MySQL组合两个表


MySQL组合两个表

  • ​​SQL架构​​
  • ​​表1: Person​​
  • ​​表2: Address​​
  • ​​编写一个 SQL 查询,满足条件:无论 person 是否有地址信息,都需要基于上述两表提供 person 的以下信息:​​
  • ​​题解​​
  • ​​方式1​​
  • ​​方式2​​

SQL架构

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');

MySQL组合两个表_MySQL

表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

题解

方法:使用 outer join

算法

因为表 Address 中的 personId 是表 Person 的外关键字,所以我们可以连接这两个表来获取一个人的地址信息。

考虑到可能不是每个人都有地址信息,我们应该使用 outer join 而不是默认的 inner join。

方式1

mysql> select firstName,LastName,City,State from Person p left join Address a on p.PersonId = a.PersonId;
+-----------+----------+------+-------+
| firstName | LastName | City | State |
+-----------+----------+------+-------+
| Allen | Wang | NULL | NULL |
+-----------+----------+------+-------+
1 row in set (0.00 sec)

​注意:如果没有某个人的地址信息,使用 where 子句过滤记录将失败,因为它不会显示姓名信息。​

方式2

select 
FirstName,
LastName,
(select City from Address a where a.PersonId=p.PersonId) as City,
(select State from Address a where a.PersonId=p.PersonId) as State
from Person p;

+-----------+----------+------+-------+
| firstName | LastName | City | State |
+-----------+----------+------+-------+
| Allen | Wang | NULL | NULL |
+-----------+----------+------+-------+
1 row in set (0.00 sec)


举报

相关推荐

0 条评论