SQL查询语句如何能够让指定的记录排在最后

2025-03-25 07:23:06
推荐回答(5个)
回答1:

方法如下:
select * from <表名> order by case when <条件> then 1 else 0 end asc

举例:
把threads表中列id值小于100的放到最后(也就是说>=100的在前面,但是顺序是不确定的,同时<100的在后面,顺序也是不确定的)
select * from threads order by case when id<100 then 1 else 0 end asc
出来的结果可能是:
id date
109 100809
110 100810
99 100812
76 100813
其中109和110谁在前面的不确定的, 99和76谁在前面也是不确定的

回答2:

通常通过排序实现。
解释:既然是特定的记录,必然有其特殊性,可以通过此特殊性条件,用order by语句进行排序实现记录的顺序调整。
sql:select * from tablename where id>5 order by id DESE;本句话的意思就是通过id降序的形式找出id大于5的所有记录。

回答3:

oracle: 两种都支持
sqlserver:只支持第二种
1. select * from tablename order by decode(colname,'指定值','指定最大值') ;

2.elect * from tablename order by case colname when '指定值' then '指定最大值' end;

回答4:

select t.*
from
(
select *,1 as pri from 表 where 关键字段='你指定记录的值'
union all
select *,2 as pri from 表 where 关键字段<>'你指定记录的值'
) t
order by t.pri desc

回答5:

这个简单啊

比如你的表字段为 COL1 COL2 COL3 该记录值为 1 2 3

你这样
select * from tb order by case when col1=1 and col2=2 and col3=3 then o else 1 end