PostgreSQL EXTO-不同的内部数组\u agg(json\u构建\u对象

PostgreSQL EXTO-不同的内部数组\u agg(json\u构建\u对象,postgresql,ecto,elixir,Postgresql,Ecto,Elixir,我试图使用array_agg将数组合并到单个记录中 这就是我现在正在尝试使用Exto PostgreSQL实现的mysql: SELECT p.p_id, p.`p_name`, p.brand, GROUP_CONCAT(DISTINCT CONCAT(c.c_id,':',c.c_name) SEPARATOR ', ') as categories, GROUP_CONCAT(DISTINCT CONCAT(s.s_id,':',s.s_name) SEPARATOR ', ') as s

我试图使用array_agg将数组合并到单个记录中

这就是我现在正在尝试使用Exto PostgreSQL实现的mysql:

SELECT p.p_id, p.`p_name`, p.brand, GROUP_CONCAT(DISTINCT CONCAT(c.c_id,':',c.c_name) SEPARATOR ', ') as categories, GROUP_CONCAT(DISTINCT CONCAT(s.s_id,':',s.s_name) SEPARATOR ', ') as shops
在PostgreSQL中,组\u CONCAT变为数组\u agg

这是可行的,但我需要使它只显示不同的类别和商店。我需要添加json_build_对象,以便不仅仅显示类别和商店的id字段:

def create_query(nil, categories, shop_ids) do
  products_shops_categories = from p in Product,
  join: ps in ProductShop, on: p.id == ps.p_id,
  join: s in Shop, on: s.id == ps.s_id,
  join: pc in ProductCategory, on: p.id == pc.p_id,
  join: c in Subcategory, on: c.id == pc.c_id,
  where: c.id in ^categories,
  where: s.id in ^shop_ids,
  group_by: [p.id, s.id],
  select: %{product: p, categories: fragment("array_agg(json_build_object('id', ?, 'name', ?))", c.id, c.name), shops: fragment("array_agg( json_build_object('id', ?, 'name', ?, 'point', ?))", s.id, s.name, s.point)}
end
当我将DISTINCT添加到数组\u agg中时,它会导致:

** (Postgrex.Error) ERROR 42809 (wrong_object_type): DISTINCT specified, but json_build_object is not an ag
gregate function
由于Pozs的建议,最终解决方案如下:

关于一匹名为“马”的马的解决方案:

我只是尝试了分类:

group_by: [p.id, p.name, p.brand],
select: %{product: p, categories: fragment("string_agg(DISTINCT CONCAT(?,':',?), ', ') AS categories", c.id, c.name), shops: fragment("json_agg( DISTINCT (?, ?, ?)) AS shop", s.id, s.name, s.point)}
它也可以工作。这取决于您希望数组采用的格式。sting\u agg是逗号分隔的字符串。

使用string\u agg而不是group\u concat:


这里面的第188行是哪一行?@Dogbert select:[p,fragmentarray\u agg,c,s]@Dogbert抱歉,是select:[p,fragmentarray\u agg,^c,s]导致了这个错误,我刚刚更新了questionarray\u aggjson\u build\u对象……将创建一个json[]类型化值注意:json值的本机数组,我怀疑您是否需要。如果您使用json数据,最简单的方法是直接聚合到json数组中,使用json[b]_agg。还要注意,DISTINCT必须进入聚合函数:不是在聚合表达式内部,而是在它之前。还要注意,json没有相等运算符,因此您必须使用jsonb和现代版本的PostgreSQL;至少9.4,但9.5更好;请指定您的版本。@pozs谢谢。这让我越过了这一行。我发布了问题解决方案的代码。
group_by: [p.id, p.name, p.brand],
select: %{product: p, categories: fragment("string_agg(DISTINCT CONCAT(?,':',?), ', ') AS categories", c.id, c.name), shops: fragment("json_agg( DISTINCT (?, ?, ?)) AS shop", s.id, s.name, s.point)}
SELECT p.p_id, 
       p.p_name, 
       p.brand, 
       string_agg(DISTINCT CONCAT(c.c_id,':',c.c_name), ', ') as categories, 
       string_agg(DISTINCT CONCAT(s.s_id,':',s.s_name), ', ') as shops
FROM ..