union 与order by
SQL需求:拿到一组成绩中, 最好成绩,和最差成绩ID
错误示范1
- 存在语法冲突
select id,score from exam_record where score is not null order by score desc limit 1
union all
select id,score from exam_record where score is not null order by score asc limit 1
错误示范2
- limit 在union之后 导致结果集被强制限制为1无法拿到想要的结果,不可以通过修改limit 2 拿到期望值
select * from
(select id,score from exam_record where score is not null order by score desc limit 1 ) max_tab
union all
select id,score from exam_record where score is not null order by score asc limit 1
正确示范3
select id from
(select id,score from exam_record where score is not null order by score desc limit 1 ) as max_tab
union all
select id from
(select id,score from exam_record where score is not null order by score asc limit 1) as min_tab