(1)连接表
可以使用外连接进行查询
select Person.FirstName,Person.LastName,Address.City,Address.State
from Person left outer join Address on Person.PersonId=Address.PersonId
(2)第二高的薪水
select distinct 检索不同的列
limit 1,1 返回从行1开始的1行
select (select distinct salary from Employee
order by salary desc limit 1,1) as SecondHighestSalary
(3)超过经理收入的员工
这一题可以使用自连接,自连接的结果就是两张表的笛卡儿积,然后再把满足条件的列筛选出来就可以了,笛卡儿积的结果如下:
select
a.Name as Employee
From
Employee as a,Employee as b
where
a.ManagerId=b.Id and a.Salary>b.Salary
(4)查找重复的邮箱
这个可以使用分组过滤,对每个邮箱统计数目,并把数目大于2的邮箱过滤出来
select email from Person group by email having count(email) >1
(5)查找从不订购的客户
可以使用左连接,然后过滤出CustomerId为空的客户
select
Customers.name as Customers
from
Customers left outer join Orders On Customers.id=Orders.CustomerId
where
Orders.CustomerId is null
(6)分数排名
select a.score,
(select count(distinct b.score) from scores b where b.score >=a.score) as Rank
from
scores a order by a.score desc