[英]Postgresql 11 - Order by integer array index
我想根據他們在數組中的 id 順序在數據庫中列出我的產品
我的數組
'{3,2,1}'::int[]
例如
SELECT id FROM product WHERE id = ANY ('{3,2,1}'::int[]);
此查詢獲取按產品 id 排序的產品
|id|
|1 |
|2 |
|3 |
但我想按數組 id 的索引列出我的產品。 像這樣 :
|id|
|3 |
|2 |
|1 |
是否有可能做到這一點 ? 我能怎么做 ?
您可以使用array_position()
:
ORDER BY array_position('{3,2,1}'::int[], id)
如果您不想重復數組兩次:
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);
您可以WITH ORDINALITY
選項WITH ORDINALITY
unnest()
數組以跟蹤每個元素的索引,將其與表連接並使用索引作為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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.