码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Combine Two Tables

时间:2015-04-16 23:39:44      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

      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 校长

 

LeetCode - Combine Two Tables

标签:

原文地址:http://www.cnblogs.com/wxisme/p/4433576.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!