(三)MySQL学习笔记

【Leecode】175. 组合两个表

解答:由于是组合两个表的信息,很容易想到连接查询,这里使用左连接

select p.Firstname,p.Lastname,q.City,q.State from Person as p left join Address as q on p.PersonId=q.PersonId;

【Leecode】176. 第二高的薪水

解答:

第一种解法: 我们很容易知道第一高的薪水(max函数),所以,除去第一高的薪水再找最高的薪水,就是第二高的薪水了

select max(Salary) as SecondHighestSalary from Employee where Salary not in (select max(Salary) from Employee);

第二种解法:按薪水从高到低排序,再找第二条数据就是第二高薪水了。limit 1表示读取一行数据, offset 1 表示从表的第二行开始读取

select Salary as SecondHighestSalary from Employee order by Salary desc limit 1 offset 1;

【Leecode】181. 超过经理收入的员工

解答:

这里涉及到同一个表中的字段值的比较,所以可以为这张表建两个别名(当作两张表)。

 第一种解法:直接找出员工的薪水和对应的经理的薪水,进行比较

select e1.Name as Employee from Employee as e1 where e1.Salary>(select e2.Salary from Employee as e2 where e1.ManagerId=e2.Id)

第二种解法:使用join连接查询,相当于把表划分为员工表和经理表,再对各自的薪水进行比较

select e1.Name as Employee from Employee as e1 join Employee as e2 where e1.ManagerId=e2.Id and e1.Salary>e2.Salary

【Leecode】182. 查找重复的电子邮箱

解答:首先想到应该就是根据 Email 分组,再计算每个分组的行数是否大于1.

select Email from Person group by Email having count(Email)>1

【Leecode】183. 从不订购的客户

解答:

第一种解法:直接查找用户表的Id不在订单表中出现过的用户即可

select Name as Customers from Customers where Id not in (select CustomerId from Orders)

 第二种解法:左连接查找。以用户表为基准,连接订单表,查找CustomerId为空的数据

select c.Name as Customers from Customers as c left join Orders as o on o.CustomersId=c.Id and o.CustomerId is null

【Leecode】196. 删除重复的电子邮箱

解答:这里涉及到同一个表中的字段值 Id 的比较,所以可以为这张表建两个别名(当作两张表)。

delete p1 from Person as p1, Person as p2 where (p1.Email=p2.Email) and (p1.Id>p2.Id) 

【Leecode】197. 上升的温度

解答:涉及到同一张表中的字段值比较,所以可以为这张表建两个别名(当作两张表),这里关键是判断日期的连续性

第一种解法:DATEDIFF函数来判断日期

select w1.Id from Weather as w1, Weather as w2 where (w1.Temperature>w2.Temperature) and DATEDIFF(w1.RecordDate, w2.RecordDate)=1;

第二种解法:TO_DATE函数来判断日期

select w1.Id from Weather as w1, Weather as w2 where w1.Temperature>w2.Temperature and TO_DAYS(w1.RecordDate)=TO_DAYS(w2.RecordDate)+1;

第三种解法:SUBDATE函数来判断日期

select w1.Id from Weather as w1, Weather as w2 where w1.Temperature>w2.Temperature and SUBDATE(w1.RecordDate,1)=w2.RecordDate;

【Leecode】595. 大的国家

解答:这里使用 or 即可

select name, population, area from World where (area>3000000) or (population>25000000)

【Leecode】596. 超过5名学生的课

解答:对 class 分组,计算分组的数据是否大于等于5即可,还要使用 distinct 去重

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

【Leecode】620. 有趣的电影

解答:这里关键是找出奇数 Id,可以巧妙使用 & 运算,奇数&1为1(True),偶数&1为0(False)

select * from cinema where description!='boring' and id&1 order by rating desc;

【Leecode】627. 交换工资

解答:可以使用 if 语句来做判断

update salary set sex=if(sex='f', 'm', 'f')
原文地址:https://www.cnblogs.com/delav/p/9929705.html