select *
from student_details
where student_rollnumber in(644,1,2)
order by student_rollnumber
union
select *
from student_details
where student_rollnumber not in(644,1,2) ;
答案 0 :(得分:3)
当ORDER BY
与UNION
一起使用时,它应该在最后。
select *
from student_details
where student_rollnumber in(644,1,2)
union
select *
from student_details
where student_rollnumber not in(644,1,2)
order by student_rollnumber;
如果student_rollnumber
为NOT NULL
,则您的查询与以下内容相同:
select DISTINCT *
from student_details
order by student_rollnumber;
答案 1 :(得分:1)
如果你想要这三个学生,那么order by
与case
一起使用,而不是union
:
select sd.*
from student_details sd
order by (case when sd.student_rollnumber in (644,1,2) then 1 else 2 end),
sd.student_rollnumber ;
您的方法不好有几个原因:
order by
结尾,否则SQL结果集将无序。UNION
效率不高,因为它有删除重复项的开销。UNION ALL
也不能保证首先返回第一个子查询值。