Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/jenkins/5.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 在Postgres中加入时保留数组中项目的顺序_Postgresql_Join_Aggregate Functions - Fatal编程技术网

Postgresql 在Postgres中加入时保留数组中项目的顺序

Postgresql 在Postgres中加入时保留数组中项目的顺序,postgresql,join,aggregate-functions,Postgresql,Join,Aggregate Functions,假设我有两个表:posts和embeddes。posts中的每个post可能都有一些与之相关联的嵌入项,这些嵌入项必须按特定顺序保留。此查询似乎有效,产生如下所示的“Post_embeds”结果: SELECT p.id AS pid, array_agg(e.code) AS code FROM posts p, unnest(p.embeds) embed_id JOIN embeds e ON e.id = embed_id GROUP BY p.id; 正如您所看到的,顺序是

假设我有两个表:postsembeddes。posts中的每个post可能都有一些与之相关联的嵌入项,这些嵌入项必须按特定顺序保留。此查询似乎有效,产生如下所示的“Post_embeds”结果:

SELECT p.id AS pid, array_agg(e.code) AS code
  FROM posts p, unnest(p.embeds) embed_id
  JOIN embeds e ON e.id = embed_id
GROUP BY p.id;

正如您所看到的,顺序是embeds。但随后我创建了一个视图post_Embeddes,并尝试查询此视图:

SELECT * FROM post_embeds WHERE pid=1
嵌入的顺序消失了。我怀疑我的第一个查询毕竟不能保证保持秩序,而这只是巧合

如何正确查询带有关联嵌入的某些帖子,保持顺序?

使用带有顺序的
unnest()
和聚合中的顺序:

SELECT p.id AS pid, array_agg(e.code ORDER BY ordinality) AS code
  FROM posts p, unnest(p.embeds) WITH ORDINALITY AS u(embed_id, ordinality)
  JOIN embeds e ON e.id = embed_id
GROUP BY p.id;
读入

如果指定了WITH ORDINALITY子句,将向函数结果列中添加一个bigint类型的附加列。此列对函数结果集的行进行编号,从1开始


我不会因为数据是以图像而不是文本的形式发布而对此进行投票。
具有有序性可以解决您的问题,但如何改为修复您的模式?您应该有一个连接表,比如
post\u x\u embed(post\u id,embed\u id,order)
,您甚至可以使用外键。。。