跟着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
相关推荐
李兆龙的博客1 小时前
问津集 #26:Lakebase——Postgres 的版本化页面存储、数据库分支与计算弹性
数据库
倔强的石头_4 小时前
聊聊金仓KFS:一款把数据同步软件做扎实的产品
数据库
闲云野鹤在人间4 小时前
MySQL|从理论、安装、备份到主从复制、MHA高可用详解
linux·运维·数据库·mysql·云计算
禾小西4 小时前
Redis:从两大维度和三大主线建立知识体系
数据库·redis·缓存
禾小西5 小时前
Redis 数据结构:快速的 Redis 有哪些慢操作?
数据结构·数据库·redis
数据库小学妹5 小时前
数据共享交换平台选型:交换方式对比与避坑指南
数据库·信创·数据同步·数据交换平台·政务数据共享·数据共享交换平台·数据库底座
要开心吖ZSH5 小时前
MySQL 慢 SQL 排查操作手册-个人笔记版
java·笔记·sql·mysql·慢查询
loong_XL6 小时前
决策模型做内容安全检测:从踩坑到上线
数据库·安全·jev·决策模型
这个DBA有点耶7 小时前
数据库双轨并行实战:全量并行策略、增量延迟控制、双向回切与一致性校验
数据库·架构·dba
adinnet20267 小时前
保单、赔付与渠道问数:保险经营数据如何实现按需查询
大数据·数据库·人工智能