Leetcode知识总结——SQL(1)

Leetcode知识总结——SQL(1)



题号:175. Combine Two Tables


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


这里关键是用到left join和on,这里的用on作为条件,即使不满足后面的条件,也会把Person表里面的FirstName和LastName选出来,后面两项则为NULL。如果是使用where作为选择的话,不满足条件的项就不会被列出来。


题号:176. Second Highest Salary


select max(Salary) as "SecondHighestSalary" from Employee where Salary < (select max(Salary) from Employee);


这里主要是用了一个嵌套来实现第二大的元素查询,利用括号里面的select语句查询的最大值作为条件,选择比它小的最大值,也就是第二大的值。


题号:181. Employees Earning More Than Their Managers


select A.Name as "Employee" from Employee as A, Employee as B where (A.ManagerId=B.Id and A.Salary>B.Salary);


这里在From处把表复制成两份:A和B,利用where可以做到自己和自己进行对比。


题号:182. Duplicate Emails


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


这里利用group by把Email元素进行聚合,然后利用having作为条件选择数量大于1的Email即为重复的Email。不用where是因为where不能和聚合一起使用。


题号:183. Customers Who Never Order


select Name as "Customers" from Customers where Customers.Id not in(Select CustomerId from Orders);


这里利用not in来选择Id不在Order表里面的元素。

猜你喜欢

转载自www.cnblogs.com/sunw26/p/12163067.html