sql - 带有 row_number 的 MySQL 连接子句
问题描述
具有下表定义:
table StudentChallenge(studentId);
table StudentLesson(studentId, schoolId, lesson, createdAt);
table Student(id, name);
schoolId == 22
我希望此查询仅返回每个学生的最新课程:
select * from
(select distinct(studentId) from StudentChallenge) sch
join (select studentId, schoolId,
row_number() over (partition by studentId order by createdAt desc) as slrn
from studentLesson where schoolId = 22) sl on sl.studentId= sch.studentId
join (select id, name from Student) s on s.id = sch.studentId
where sl.slrn = 1;
但令人惊讶的是,它返回带有schoolId = 22
和其他值的行!
当我删除第三个联接(与学生表联接)时,一切正常!
如果我删除row_number()
部分查询,它工作正常!
此外,如果我移动where schoolId = 22
到附近的查询结束,sl.slrn = 1
它工作正常!
认为它有一些row_number
子句,任何人都可以解释这种行为吗?
解决方案
推荐阅读
- css - 如何在多个字符串上使用 CSS 应用类型编写器动画
- java - 设置列表首选项后,为什么我的应用程序不会更改为暗模式 (Android Q)?
- python - 如何按字典值搜索带有嵌套字典的列表,返回带有字典元素的列表索引
- java - 如何从 Intstream 创建 ArrayList
- javascript - Switch 语句不执行相应的块
- android - FirebaseAuth 监听器没有被调用
- python - Pygame Collidepoint 函数未按预期工作
- java - Kakfa consumer.poll 不返回 2.4.0 的记录
- c++ - 我希望两个循环并行运行
- javascript - 当用户关闭移动浏览器窗口时如何采取行动?