在 postgres 中选择时保留顺序

yiw*_*wen 3 sql postgresql

在 psql 中(至少在 v9 中),如果我这样做

select id from users where id in (2, 1, 1);
Run Code Online (Sandbox Code Playgroud)

select id from users where id in (1, 2);
Run Code Online (Sandbox Code Playgroud)

它们都以相同的顺序返回结果(并消除重复),例如:1, 22, 1, 1如何在第一个查询中返回?

Lau*_*lbe 6

你不能; 顺序将取决于执行计划、表的物理顺序和其他因素。

您可以使用数组和显式来做到这一点ORDER BY

SELECT u.id
FROM users AS u
   JOIN unnest(ARRAY[2,2,1]) WITH ORDINALITY AS arr(elem, ord)
      ON u.id = arr.elem
ORDER BY arr.ord;
Run Code Online (Sandbox Code Playgroud)