跟着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
相关推荐
eLIN TECE11 分钟前
nacos2.3.0 接入pgsql或其他数据库
数据库
曾几何时`30 分钟前
MySQL(七)索引
数据库·mysql
KmSH8umpK1 小时前
Redis分布式锁从原生手写到Redisson高阶落地,附线上死锁复盘优化方案进阶第九篇
数据库·redis·分布式
悠悠121381 小时前
一条 SQL 从敲下回车,到在 MySQL 里“跑完一生”,中间到底经历了啥?
数据库·sql·mysql
秋91 小时前
MySQL 9.7.0 使用详解:新特性、实战与避坑指南
android·数据库·mysql
S1998_1997111609•X1 小时前
恶意注入污染蜜罐HDMI进程函数值进行封禁垃圾蠕虫仓蟲的轮系依据行为戆直㞢仓shell token
数据库·爬虫·网络协议·百度·开闭原则
Yupureki1 小时前
《Redis数据库》1.初识Redis
数据库·redis·缓存
Lyyaoo.1 小时前
Redis实现分布式锁
数据库·redis·分布式
张~颜2 小时前
autovacuum
数据库·postgresql
山峰哥2 小时前
SQL优化从入门到精通:20个案例破解性能密码
数据库·sql·oracle·性能优化·深度优先