本文介绍了执行查询后数据集的自定义排序顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望数据库查询的结果集具有一定的顺序。我想要订阅的信息不包含在数据库中,但是在代码中动态生成(因此我不能使用 ORDER BY )。

I want the result set of a database query to have a certain order. The information I want to order by is not contained in the database, but dynamically generated in code (so I cannot use ORDER BY).

执行数据库查询后有没有办法排序数据集? (我不需要索引访问,但只需要遍历所有记录。)

Is there a way to sort a dataset after executing the database query? (I don't need indexed access but only want to iterate over all records.)

推荐答案

有一种共享相似之处的可能性与Jens的答案(+1),但以略有不同的方式得到结果。

There is a possibility that shares similarities with Jens' answer (+1) but gets to the result in a slightly different fashion.

给定一个现有的表:

create table somedata (id integer, name char(20));
insert into somedata values ( 1, 'Tim' );
insert into somedata values ( 2, 'Bob' );
insert into somedata values ( 3, 'Joe' );

如果您知道所需的短单(通过处理表或其中的一些查询结果)创建一个具有一些关键值的临时表,以匹配原始表中所需的行,然后排序顺序数据:

If you know the desired short order (either by processing the table or some query result from it), create a temp table that has some key value to match the desired rows from the original table and then the sort order data:

create table #sortorder( id integer, sortvalue integer );

在临时表中设置 sortvalue 字段包含所需的顺序(它可以是任何可排序的数据类型 - 不必是整数):

Set the sortvalue field in the temp table to contain the desired order (it could be any sortable data type - doesn't have to be integer):

insert into #sortorder values ( 1, 15 );
insert into #sortorder values ( 2, 12 );
insert into #sortorder values ( 3, 5 );

然后根据提供排序顺序的表生成具有连接的结果:

Then generate the results with a join against the table that provides the sort order:

select sd.* from somedata sd, #sortorder so
         where sd.id = so.id
         order by so.sortvalue;

这篇关于执行查询后数据集的自定义排序顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 04:13