Ker*_*kır 7 sql arrays postgresql sql-order-by postgresql-11
我想根据数组中的 id 顺序在数据库中列出我的产品
我的阵列
'{3,2,1}'::int[]
Run Code Online (Sandbox Code Playgroud)
例如
SELECT id FROM product WHERE id = ANY ('{3,2,1}'::int[]);
Run Code Online (Sandbox Code Playgroud)
此查询获取按产品 id 排序的产品
|id|
|1 |
|2 |
|3 |
Run Code Online (Sandbox Code Playgroud)
但我想列出按数组 id 的索引排序的产品。像这样 :
|id|
|3 |
|2 |
|1 |
Run Code Online (Sandbox Code Playgroud)
是否有可能做到这一点 ?我能怎么做 ?
您可以unnest()使用选项WITH ORDINALITY来跟踪每个元素的索引,将其与表连接并使用索引作为ORDER BY条件:
SELECT p.id
FROM product AS p
INNER JOIN unnest('{3,2,1}'::int[]) WITH ORDINALITY AS a(id, nr)
ON p.id = a.id
ORDER BY a.nr;
Run Code Online (Sandbox Code Playgroud)
您可以使用array_position():
ORDER BY array_position('{3,2,1}'::int[], id)
Run Code Online (Sandbox Code Playgroud)
如果您不想重复数组两次:
select p.id
from product p join
(values ('{3,2,1}'::int[])) v(ar)
on p.id = any(v.ar)
order by array_position(v.ar, p.id);
Run Code Online (Sandbox Code Playgroud)