跟着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
相关推荐
凌虚5 小时前
面向 MySQL 用户的 PostgreSQL 快速上手指南
数据库·后端·架构
五阿哥永琪5 小时前
MySQL中操作json的函数!
数据库·mysql·json
来者皆善5 小时前
了解Mysql优化吗?如何优化索引?
数据库·mysql
赤壁小虾7 小时前
【渲染流水线】[逐片元阶段]-[透明度测试]以UnityURP为例
java·前端·数据库
MC皮蛋侠客7 小时前
SQLAlchemy 系列(七):高级建模与高效写入——批量 DML、方言与扩展
数据库·python
奈斯先生Vector8 小时前
把 Midjourney 二次编辑做成生产系统:customId 能力令牌、Action Graph 与 WebUI 精修工作台
数据库·人工智能·架构·aigc·音视频·midjourney
Lethehong9 小时前
双擎并驱·全链路并行:KFS让TB级异构增量同步秒级到达
数据库
MC皮蛋侠客9 小时前
SQLAlchemy 系列(八):AsyncIO、并发与 Web 生命周期——让每个并发任务持有自己的 Session
数据库·python
一水9 小时前
Redis实战:一个AI工作流系统里的五个应用场景,从传参到限流的完整链路
数据库·redis·wpf
枫叶v.10 小时前
Prompt Injection 防不住怎么办?从 Source-Sink 模型设计 Agent 安全边界
数据库·安全·prompt