跟着AI学sql

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
相关推荐
啦啦啦_99992 小时前
1. MySQL
数据库·mysql·oracle
随风,奔跑2 小时前
MySQL性能调优
数据库·mysql·oracle
QH139292318802 小时前
是德科技KEYSIGHT N5183B 9 kHz~40 GHz微波模拟信号发生器
网络·数据库·科技·嵌入式硬件·集成测试
暗暗别做白日梦2 小时前
Redisson 延迟队列实现订单支付超时自动取消(源码 + 原理全解)
数据库·redis
数厘2 小时前
2.13 sql数据更新(UPDATE)
数据库·sql·oracle
一江寒逸2 小时前
零基础从入门到精通MongoDB(附加篇):面试八股文全集
数据库·mongodb·面试
星晨雪海3 小时前
Redis 分布式 ID 生成器
数据库·redis·分布式
有味道的男人3 小时前
抖音关键词搜索,视频详情api
linux·数据库·音视频
丁丁点灯o3 小时前
Oracle中金额数字转换为大写汉字
数据库·oracle