开发者

Postgres subquery, ordering by subquery

开发者 https://www.devze.com 2022-12-22 14:27 出处:网络
If I have a query such as : select * from tbl where id in (10, 20, 9, 4); the results returned could potentially be in this order:

If I have a query such as :

select * from tbl where id in (10, 20, 9, 4);

the results returned could potentially be in this order: 4, 9, 10, 20开发者_开发知识库

but what if was looking to maintain the order of the list passed into the initial query? how would you approach this?

Ultimately I'm using Django as the ORM for my app here but I'm looking to investigate what is feasible at db level first.

Any ideas most welcome!


Using CASE isn't very portable because you have to know ahead of time all of the values and the order that you want to sort. The cleanest way is to use an array for the values and sort by the item's index in the array.

I had posted this to the Postgres Snippet Library a while back.

CREATE OR REPLACE FUNCTION idx(anyarray, anyelement)
  RETURNS int AS 
$$
  SELECT i FROM (
     SELECT generate_series(array_lower($1,1),array_upper($1,1))
  ) g(i)
  WHERE $1[i] = $2
  LIMIT 1;
$$ LANGUAGE sql IMMUTABLE;

SELECT * FROM foo ORDER BY idx(array['Freshman','Sophomore','Junior','Senior'], foo.grade_level)


You might then want to look at using a CASE in the ORDER BY statement


Take a look at this topic to see how you can create an array and use it to sort in a function. Works great!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号