博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Leetcode|SQL] Combine Two Tables
阅读量:5130 次
发布时间:2019-06-13

本文共 1684 字,大约阅读时间需要 5 分钟。

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

 

Solution:

Whenever we need to combine records from two or more tables, we need to join the tables. There are two common types of join and it is important to understand their differences:

  • Inner Join - Selects only records from both tables that have matching values. This is also the default join.
  • Outer Join - Does not require each record in the two joined tables to have a matching record.
    • Left Outer Join - Returns all values from the left table, even if there is no match with the right table.

Since the question requires information for each person regardless if there is an address for that person, the answer is to use an outer join.

You may use either a LEFT JOIN (Person LEFT JOIN Address) or a RIGHT JOIN (Address RIGHT JOIN Person).

 

Ans:

# Write your MySQL query statement below

SELECT Person.FirstName, Person.LastName, Address.City, Address.State FROM Person LEFT JOIN Address ON Person.PersonId=Address.PersonId

转载于:https://www.cnblogs.com/Phoebe815/p/4225394.html

你可能感兴趣的文章
【PHP】在目标字符串指定位置插入字符串
查看>>
【JS】jQuery设置定时器,访问服务器(PHP示例)配合微信、支付宝原生支付,跳转web网页...
查看>>
实验四2
查看>>
在小程序开发的新风口 看华为云如何助立创科技抢占市场红利
查看>>
第一次博客随笔:苏钰冰
查看>>
HIS-DELPHI-读取数据库配置
查看>>
如何引入iconfont图标与Element-UI组件
查看>>
ArcMap合并之路 -- 该段路合并成一个完整的路
查看>>
在UC浏览器打开链接唤醒app,假设没有安装该app,则跳转到appstore下载该应用
查看>>
skozrloug
查看>>
D. Flowers Codeforces Round #271(div2)
查看>>
表单重复提交
查看>>
HDU2767 Proving Equivalences(scc)
查看>>
shell脚本函数与数组
查看>>
HDU - 2825(AC自动机+状态压缩DP(需要优化))
查看>>
论Nim中的 proc 和 method
查看>>
Arch linux配置指南
查看>>
external panel
查看>>
【luogu2667】 超级质数 - DFS
查看>>
Bash快捷键
查看>>