版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/qq_30650153/article/details/81782098
175. Combine Two Tables
1、 题目与答案
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
表中的每个人提供以上信息,而不管这些人是否有一个地址:
答案是:
select
p.FirstName, p.LastName, a.City, a.State
from
Person p left join Address a on p.PersonId = a.PersonId ;
2、知识点总结
- 多表
left join
是会生成一张临时表,并返回给用户 A left join B ON
条件表达式ON
子句和WHERE
子句有什么不同?
ON
条件(“A left join B ON
条件表达式”中的ON
)用来决定如何从 B 表中检索数据行。如果 B 表中没有任何一行数据匹配ON
的条件,将会额外生成一行所有列为 NULL
的数据。
而在匹配阶段 WHERE
子句的条件都不会被使用。仅在匹配阶段完成以后,WHERE
子句条件才会被使用。它将从匹配阶段产生的数据中检索过滤。
参考链接:
mysql left join中where和on条件的区别
关于 MySQL LEFT JOIN 你可能需要了解的三点