Mysql实现"组合两个表"的一种方法

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.

写一个SQL查询,在Person表中查询每一个人的如下信息,无论这个人是否存在地址信息

FirstName, LastName, City, State

1:简单的join操作

JOIN 按照功能大致分为如下三类:

  • INNER JOIN(内连接,或等值连接):获取两个表中字段匹配关系的记录。
  • LEFT JOIN(左连接):获取左表所有记录,即使右表没有对应匹配的记录。
  • RIGHT JOIN(右连接): 与 LEFT JOIN 相反,用于获取右表所有记录,即使左表没有对应匹配的记录。
select FirstName, LastName, City, State from Person left join Address on Person.PersonId=Address.PersonId

 算法题来自:https://leetcode-cn.com/problems/combine-two-tables/description/

猜你喜欢

转载自blog.csdn.net/qiubingcsdn/article/details/82670373