Limit在嵌套中使用的解决方法
select xh,sum(cj)
from cjb
group by xh
order by sum(cj) desc
执行结果:
#查询个人总成绩前三名的学生姓名
select xh,xm
from xsb
where xh in(select xh from cjb
group by xh
order by sum(cj) desc
limit 3)
执行结果:
解决方案一:为limit子句加一层嵌套
select xh,xm
from xsb
where xh in
(select a.xh from (select xh from cjb
group by xh
order by sum(cj) desc
limit 3) a)
执行结果:
注意:结果显示的顺序错误
解决方案二:把限制条件放到from而非where子句中(更好的方法)
select xm
from xsb ,(select xh from cjb group by xh order by sum(cj) desc limit 3) as b
where xsb.xh=b.xh
执行结果:
#查询个人总成绩前三名的学生的学号、姓名、总分
select xsb.xh,xm,zcj
from xsb ,(select xh ,sum(cj) as zcj from cjb group by xh order by sum(cj) desc limit 3) b
where xsb.xh=b.xh
执行结果:
解决方案三:使用等值或内连接
select xsb.xh,xm
from xsb,cjb
where xsb.xh=cjb.xh
group by xsb.xh
order by sum(cj) desc
limit 3