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表中的每个人提供FirstName、LastName、City、和State,无论这些人是否有地址:
解法一:
SELECT a.FirstName, a.LastName, b.City, b.State FROM Person as a LEFT JOIN Address as b on a.PersonId = b.PersonId;
解法二:
可以使用关键字NATURAL,这样我们就不要申明具体的列了,MySQL可以自行搜搜相同的列:
SELECT a.FirstName, a.LastName, b.City, b.State FROM Person as a NATURAL LEFT JOIN Address as b;
解法三:
在使用LEFT JOIN时,我们也可以使用关键字USING来申明我们想用哪个列名来进行联合:
SELECT a.FirstName, a.LastName, b.City, b.State FROM Person as a LEFT JOIN Address as b USING(PersonId);