您的位置:首页 > 其它

【leetcode】 database Combine Two Tables

2015-08-04 22:41 585 查看
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


题目很是简单,合并两个表。

本来以为很easy,后来发现确实很easy。 = =

WA sql:

<span style="font-size:18px;"></span><pre name="code" class="sql">SELECT p.FirstName, p.LastName, a.City, a.State
FROM Person as p, Address as a
WHERE p.PersonId = a.PersonId;




这个sql会出现错误,以为是内连接。会自动消除一些没有匹配的记录。

正确的sql,应该用外链接。

sql:

SELECT p.FirstName, p.LastName, a.City, a.State
FROM Person as p LEFT OUTER JOIN Address as a
ON p.PersonId = a.PersonId;
or sql:

SELECT p.FirstName, p.LastName, a.City, a.State
FROM Address as a RIGHT OUTER JOIN Person as p
ON p.PersonId = a.PersonId;


使用LEFT OUTER JOIN or RIGHT OUTER JOIN 都是可以的。

我们需要注意的有两点:

1,外部联接中,OUTER JOIN 是用ON 类进行 匹配(说过滤好像不太准确)的。

2,LEFT 和 RIGHT 的区别是 一 哪个为全。 具体详情可以查看/article/1812121.html

主要还是认识了,外联接的一些知识。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: