MySQL学习笔记(三)【Leecode】

【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

猜你喜欢

转载自www.cnblogs.com/delav/p/9929705.html