使PostgreSQL尊重输入参数的顺序?

Bry*_*oso 5 python postgresql

这个问题有一点历史 - 有没有办法让查询尊重输入参数的顺序?

我是新建的"专用"查询,所以我假设如果我提供一个IN子句作为SELECT查询的一部分,它将以相同的顺序返回结果.不幸的是,事实并非如此.

SELECT * FROM artists WHERE id IN (8, 1, 2, 15, 14, 3, 13, 31, 16, 5, 4, 7, 32, 9, 37)
>>> [7, 32, 3, 8, 4, 2, 31, 9, 37, 13, 16, 1, 5, 15, 14]
Run Code Online (Sandbox Code Playgroud)

(没有包括我使用Python循环遍历结果并将ID附加到列表的步骤.)

所以问题是,有没有办法让Postgres IN通过返回相同顺序的结果来尊重子句中给出的参数的顺序?

cop*_*360 5

除非您指定ORDER BY子句,否则查询结果将以非确定性顺序返回.

如果您真的想以您请求的方式进行查询,那么您可以构造这样的子句.这是使用部分数据的示例.

create table artists (
id integer not null primary key,
name char(1) not null);

insert into artists
values
    (8, 'a'),
    (1, 'b'), 
    (2, 'c'),
    (15, 'd'),
    (14, 'e'),
    (3,  'f'),
    (13, 'g');

select *
from artists
where id in (8, 1, 2, 15, 14, 3, 13)
order by
    id = 8 desc,
    id = 1 desc,
    id = 2 desc,
    id = 15 desc,
    id = 14 desc,
    id = 3 desc,
    id = 13 desc;
Run Code Online (Sandbox Code Playgroud)

基于此和您的其他问题,我认为您的模型或您尝试这样做的方式有问题.也许你应该发布一个更通用的问题,关于如何做你想做的事情.

如果你有艺术家和排名表,你应该能够做这样的事情(或通过你的ORM等效).

select
    a.*
from
    artists a,
    rankings r
where
    a.id = r.artist_id
order by
    r.score desc;
Run Code Online (Sandbox Code Playgroud)