跟着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 天前
《Kingbase护城河》——数据库存储空间全景探测与精细化瘦身实战
数据库
云技纵横1 天前
唯一索引 INSERT 死锁实战:5 秒复现交叉插入的 S 锁循环等待
sql·mysql
冬奇Lab2 天前
每日一个开源项目(第134篇):Zvec - 阿里开源的嵌入式向量数据库,向量搜索界的 SQLite
数据库·人工智能·llm
ClouGence2 天前
Oracle CDC 架构优化:从主库直连到 DataGuard 备库同步
数据库·后端·oracle
无响应de神2 天前
三、用户与权限管理
数据库·mysql
麦聪聊数据3 天前
数据服务化时代:企业数据能力输出的核心路径
数据库
shushangyun_3 天前
2026年快消品B2B系统推荐:支持终端门店订货、促销政策自动化的工具?
java·运维·网络·数据库·人工智能·spring·自动化
DARLING Zero two♡3 天前
【MySQL数据库】数据类型与表约束
数据库·mysql
曹牧3 天前
Oracle EXPLAIN PLAN
数据库·oracle
BD_Marathon3 天前
SQL学习指南——视图
数据库·sql