首页 > 解决方案 > 带有 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子句,任何人都可以解释这种行为吗?

标签: sqljoinmariadbrow-number

解决方案


推荐阅读