【LeetCode-数据库】-20201025

【LeetCode-数据库】-20201025

175.组合两个表

表1: Person

+-------------+---------+
| 列名         | 类型     |
+-------------+---------+
| PersonId    | int     |
| FirstName   | varchar |
| LastName    | varchar |
+-------------+---------+

PersonId 是上表主键
表2: Address

+-------------+---------+
| 列名         | 类型    |
+-------------+---------+
| AddressId   | int     |
| PersonId    | int     |
| City        | varchar |
| State       | varchar |
+-------------+---------+

AddressId 是上表主键

编写一个 SQL 查询,满足条件:无论 person 是否有地址信息,都需要基于上述两表提供 person 的以下信息:FirstName, LastName, City, State

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combine-two-tables
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

答案

select
    Person.FirstName,Person.LastName,Address.City,Address.State
    from Person left join Address on Person.PersonId=Address.PersonId;

知识点:

1.无论表2是否存在对应id的记录,都要显示表1内的信息,则使用"select xx,xx,xx from A left join B…
2.使用left join时 用on 不用where

176.第二高薪水

编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null

+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/second-highest-salary
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

*参考了评论区解法

答案1:

select 
	(select distinct salary 
	from Employee 
	order by salary desc limit 1,1)
	 as SecondHighestSalary 

1.DISTINCT 关键词用于返回唯一不同的值
2.按照薪资降序排序 并且只显示第二条 拓展SQL SELECT TOP, LIMIT, ROWNUM 子句
3. select xx as xxxx 赋值给后者 如果不存在查询结果 则会输出null
4.此方法数据量越大速度优势越明显

答案2

select distinct max(salary) as SecondHighestSalary 
from employee 
where salary < (select max(salary) from employee)

去掉最高新书的最高薪水

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值