有没有办法返回按“WHERE IN”值的顺序排序的SELECT结果?

时间:2014-10-11 05:29:21

标签: sql postgresql

说我有电话

SELECT * FROM tablename WHERE id IN (5,3,8,9);

返回id为3,5,8,9的结果。有没有办法让它以给定的5,3,8,9顺序返回结果?

6 个答案:

答案 0 :(得分:4)

另一个选项更灵活,因为您只需要更改一次ID。

with id_list (id, sort_order) as (
  values (5,1), (3,2), (8,3), (9,4)
)
select t.*
from tablename
  join id_list l on l.id = t.id
order by l.sort_order;

如果需要插入新的ID,维护sort_order有点难看。

随着即将到来的9.4,这将更加容易:

with id_list (id, sort_order) as (
   select *
   from unnest(array[5,3,8,9]) with ordinality
)
select *
from tablename
  join id_list l on l.id = t.id
order by l.sort_order;

这个可以使用pre 9.4完成,但是这取决于 保证的非强制函数的顺序,以提供一致的排序(但实际上它似乎总是一样的):

with id_list (id, sort_order) as (
   select *, row_number() over ()
   from unnest(array[5,3,8,9]) 
)
select *
from tablename
  join id_list l on l.id = t.id
order by l.sort_order;

答案 1 :(得分:3)

SELECT * FROM tablename WHERE id IN (5,3,8,9)
ORDER BY 
CASE id
    WHEN 5 THEN 1
    WHEN 3 THEN 2
    WHEN 8 THEN 3
    WHEN 9 THEN 4
    ELSE 5
  END

<强> Fiddle

答案 2 :(得分:1)

您也可以使用明确的join

来完成此操作
with vals as (
      select 5 as id, 1 as ordering union all
      select 3, 2 union all
      select 8, 3 union all
      select 9, 4
     )
select t.*
from tablename t join
     vals v
     on t.id = v.id
order by v.ordering;

这允许您只创建一次列表。

答案 3 :(得分:0)

在postgres中,使用POSITION:

SELECT *
FROM tablename
WHERE id IN (5,3,8,9)
ORDER BY POSITION(',' || id || ',' IN ',5,3,8,9,')

请参阅SQLFiddle


在mysql中,使用FIELD()函数:

SELECT *
FROM tablename
WHERE id IN (5,3,8,9)
ORDER BY FIELD(id,5,3,8,9)

请参阅SQLFiddle

答案 4 :(得分:0)

您也尝试这种替代方案

select *
from Table1
where id in (5,3,8,9)
order by position(id::text in '5,3,8,9')

sqlfiddle


position

答案 5 :(得分:0)

-- some data
DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp ;
SET search_path=tmp;

CREATE TABLE tablename
        ( id serial PRIMARY KEY
        , blah integer
        );
INSERT INTO tablename(blah)
select gs
FROM generate_series(1,10) gs;

-- The query
SELECT * FROM tablename t
JOIN ( SELECT id
        , row_number() OVER () AS rnk
        FROM unnest(array[ 5,3,8,9]  ) AS id
        ) val USING(id)
ORDER BY val.rnk
        ;

结果:

DROP SCHEMA
CREATE SCHEMA
SET
CREATE TABLE
INSERT 0 10
 id | blub | rnk 
----+------+-----
  5 |    5 |   1
  3 |    3 |   2
  8 |    8 |   3
  9 |    9 |   4
(4 rows)