1、左连接(返回左表全部) l e f t j o in . . o n . . . .
表1 Person(PersonId,FirstName,LastName)
表2 Address(AddressId,PersonId,City,State)
查询每个人的姓、名、城市、州,没有人的地址也要显示
select p.FirstName,p.LastName,a.City,a.State
from Person p
left join Address a
on p.PersonId = a.PersonId;
2、求第二高薪水
表 Employee(id,salary)
select salary from Employee
order by salary desc
limit 1 offset 1
3、超过经理收入的员工
表Employee(id,name,salary,managerId)
select e1.name as Employee from Employee e1
join Employee e2
on e1.managerId = e2.id
where e1.salary > e2.salary
4、查找重复电子邮箱
表Person(id,email)
select email from Person group by email
where having count(emil)>1
5、从不买东西的客户
Customers(id,name), Orders(id,customerId)
select name from Customers where
id not in (select customerId from Orders)
解法2
select c.name as Customers from Customers c
left join Orders o
on c.id=o.customerId
where o.id is null
6、超过5名学生的课
Courses(studnet,class)
select class from Courses group by class
having count(distinct student) >= 5
注意
where是分组之前过滤,having是分组之后过滤
先where在group by,先groupby在having
where->groupby->having