Leetcode database 刷题 MySQL 简单部分

Leetcode database 刷题

MySQL简单部分
176# 查第二高的工资
取第二高的工资

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

这里的distinct为了防止有重复的工资;
当employee表里只有一条数据时,也就是说没有第二高的工资,内层select语句返回结果是null,当把内层当成临时表,外层select可以输出结果,无论是不是null。(或者用if null)

SELECT
    IFNULL(
      (SELECT DISTINCT Salary
       FROM Employee
       ORDER BY Salary DESC
        LIMIT 1 OFFSET 1),
    NULL) AS SecondHighestSalary

limit a,b 也可以写成limit a offset b,都表达跳过b个,取a个值。

181# 找出工资比经理高的员工
找出工资比经理高的员工

select a.name as 'employee' 
	from employee a join employee b 
	on a.managerid=b.id
where a.salary>b.salary

需要搞清楚谁是主表

182# 找到重复的邮箱
找到重复的邮箱

select email from person group by email having count(email)>1

注意group by, having, where的应用场景,一个句子里的顺序是where, group by, having。where里不能有聚合函数。

183# 选出没有订单的客户
选出没有订单的客户

select c.name as customers 
from customers c where c.id 
	not in (select orders.customerid from orders)

not in 的用法

196# 删除重复邮件
删除重复邮件

DELETE p1 FROM Person p1,
    Person p2
WHERE
    p1.Email = p2.Email AND p1.Id > p2.Id

需要注意delete的用法:DELETE t1 FROM t1 LEFT JOIN t2 ON t1.id=t2.id WHERE t2.id IS NULL(多表删除)

197# 查温度比昨天高的序号
查温度比昨天高的序号

SELECT w2.Id
FROM Weather w1, Weather w2
WHERE DATEDIFF(w2.RecordDate, w1.RecordDate) = 1
AND w1.Temperature < w2.Temperature

对这种要自己和自己比较的题目,先用自连接,这题要再利用datediff函数

511# 512# 游戏玩法分析
使用min函数和嵌套联合查询
577# 员工奖金
注意null值也要显示在结果内
584# 寻找用户推荐人
is null/is not null的用法
!=/<>表示不等关系
586# 订单最多的客户
count(*)
595# 大的国家
大的国家

select name, population, area from world where population>25000000 or area>3000000

596# 大于五个人
大于五人

select class from courses group by class having count(distinct student)>=5

597# 好友请求
round()取小数后2位,if null判断是否为空

select count(*) from (select distinct sender_id,send_to_id from friend_request)

603# 连续空余座位
自连接和数字推断
607# 销售员
not in的使用
610# 判断三角形
三角形任意两边之和大于第三边,任意两边之差小于第三边。 case…when…

CASE
        WHEN x + y > z AND x + z > y AND y + z > x THEN 'Yes'
        ELSE 'No'
    END AS 'triangle'

613# 直线上最短的距离
abs取绝对值看距离,min取最短距离
619# 只出现一次的最大数字
max
620# 有趣的电影
有趣的电影

select * from cinema where description !='boring' and mod(id,2)=1 order by rating desc

mod取余数

627# 交换工资
交换工资

update salary set sex=case sex when 'm' then 'f' else 'm' end

update的用法,case when的用法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值