Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PostgreSQL-按数组的位置排序,并在另一列上区分_Postgresql_Sql Order By_Distinct On - Fatal编程技术网

PostgreSQL-按数组的位置排序,并在另一列上区分

PostgreSQL-按数组的位置排序,并在另一列上区分,postgresql,sql-order-by,distinct-on,Postgresql,Sql Order By,Distinct On,我有一个类似这样的查询(实际的查询和表更复杂): 这给了我一个按特定顺序排列的类别名称列表(数组传递的uuid顺序)。例如: 789 CDX "Cat D" 123 KDJ "Cat A" 456 PLM "Cat B" 123 OLA "Cat F" 456 OWK "Cat X" 123 CAT "Cat Z" 我想做的是在该查询中添加一个独特的ON'item.other_uid'。因此,得出的清单将是: 789 CDX "Cat D" 123 KDJ "Cat A" 456 CAT "C

我有一个类似这样的查询(实际的查询和表更复杂):

这给了我一个按特定顺序排列的类别名称列表(数组传递的uuid顺序)。例如:

789 CDX "Cat D"
123 KDJ "Cat A"
456 PLM "Cat B"
123 OLA "Cat F"
456 OWK "Cat X"
123 CAT "Cat Z"
我想做的是在该查询中添加一个独特的ON'item.other_uid'。因此,得出的清单将是:

789 CDX "Cat D"
123 KDJ "Cat A"
456 CAT "Cat B"

我怎样才能做到这一点?Postgres希望ORDER BY&DISTINCT匹配,但这不是我查询的正确顺序


我试图将其作为一个子查询,并在主查询中使用DISTINCT,但没有维护顺序…

这里有两个组件,为每组“other_uuid”选择哪个成员,以及这些选定行的显示顺序。如果您希望同时管理这两件事,可能需要一个内部查询和一个外部查询,每个查询都有自己的ORDERBY

select * from (
   SELECT distinct on (other_uuid)other_uuid, uuid, name
   FROM ...
   ORDER BY other_uuid, array_position(ARRAY['CDX', 'KDJ', 'PLM', 'OLA', 'OWK', 'CAT']::text[], uuid), name
) foo order by array_position(ARRAY['CDX', 'KDJ', 'PLM', 'OLA', 'OWK', 'CAT']::text[], uuid);

数组_位置表达式的重复很难看。有很多方法可以避免,但这些方法也很难看。

@jjanes你是对的,我在我的例子中犯了一个错误。我刚刚更新了它。第一列是“other_uuid”,数组位置不正确。
select * from (
   SELECT distinct on (other_uuid)other_uuid, uuid, name
   FROM ...
   ORDER BY other_uuid, array_position(ARRAY['CDX', 'KDJ', 'PLM', 'OLA', 'OWK', 'CAT']::text[], uuid), name
) foo order by array_position(ARRAY['CDX', 'KDJ', 'PLM', 'OLA', 'OWK', 'CAT']::text[], uuid);