LeetCode - Combine Two Tables

      Description: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:     

    第一次刷SQL题目感觉还是不错的。这个题目大概是说把第一张表和第二张表连接起来。而且第二张表中的Person的Address中的属性可能为NULL。这明显就是个左外链接。

   

# Write your MySQL query statement below
SELECT FirstName ,LastName, City, State 
FROM Person LEFT OUTER JOIN Address ON (Person.PersonId=Address.PersonId);

 

 这里需要说一下左外链接和右外链接的区别。

      左外链接是列出左边关系的所有元组,右外链接是列出右边关系的所有元组。下面举个例子。
      PersonName(id,name)
      数据:(1,张三)(2,李四)(3,王五)
      PersonPosition(id,position)
      数据:(1,学生)(2,老师)(4,校长)

      左连接的结果:

      select PersonName.*,PersonPosition.* from PersonName left join PersonPosition on PersonName.id=PersonPosition.id;
      1 张三 1    学生
      2 李四 2    老师
      3 王五 NULL NULL

      右外链接的结果:

      select PersonName.*,PersonPosition.* from PersonName right join PersonPosition on PersonName.id=PersonPosition.id;

      1    张三 1 学生
      2    李四 2 老师
      NULL NULL 4 校长

 

posted @ 2015-04-16 22:48  Pickle  阅读(156)  评论(0编辑  收藏  举报