SELECT
t1.*, (
SELECTcount(*)
FROM
grade t2
WHERE
t1.score <= t2.score
AND t1.c_id = t2.c_id
) AS rownum
FROM
grade t1
查询结果
c_id
s_id
score
rownum
1
1
80
3
1
2
90
2
1
3
70
4
1
4
95
1
2
1
64
4
2
2
88
2
2
3
89
1
2
4
79
3
3
1
90
2
3
2
80
4
3
3
96
1
3
4
85
3
4
1
88
2
4
2
90
1
4
3
50
4
第二步 将第一步所的表命名为t3 然后将表中rownum为3的查询出来 并按学科排序
查询代码
SELECT
*
FROM
(
SELECT
t1.*, (
SELECTcount(*)
FROM
grade t2
WHERE
t1.score <= t2.score
AND t1.c_id = t2.c_id
) AS rownum
FROM
grade t1
) t3
WHERE
rownum = 3ORDERBY
c_id
查询结果
c_id
s_id
score
rownum
1
1
80
3
2
4
79
3
3
4
85
3
4
4
60
3
第三步 对最终查询结果与 student cource 两表进行左连接
查询代码
SELECT
student.s_no,
student.s_name,
course.c_name,
grade_temp.score
FROM
(
SELECT
*
FROM
(
SELECT
t1.*, (
SELECTcount(*)
FROM
grade t2
WHERE
t1.score <= t2.score
AND t1.c_id = t2.c_id
) AS rownum
FROM
grade t1
) t3
WHERE
rownum = 3ORDERBY
c_id,
score DESC
) grade_temp
LEFTJOIN course ON grade_temp.c_id = course.c_id
LEFTJOIN student ON grade_temp.s_id = student.s_id