postgresql SQL错误无法识别类型json的相等运算符

xcitsw88  于 11个月前  发布在  PostgreSQL
关注(0)|答案(1)|浏览(184)

我遇到了这个问题:
repeated rows in json_agg() in query with 2 lateral joins
我的列上有重复的行,所以我想尝试一个例子,但现在我得到了这个错误:

error: could not identify an equality operator for type json

个字符
我做错了什么?
DB FIDDLE示例

bttbmeg0

bttbmeg01#

正如错误所说,您无法比较Json值。查询的group by部分是导致问题的原因,因为您试图按json字段(c.product_options)分组,而您甚至不需要。一个解决方案是将group by作为

SELECT 
      p.id,
      p.shop_id,
      p.provider_id,
      p.name,
      p.status,      
      c.product_options      
FROM product p      
left join lateral (
  select json_agg(json_build_object(
    'id', po.id,
    'p_id', po.p_id,
    'name', po.name
  )) AS product_options      
  from product_options po        
  where p.id = po.p_id        
  ) c on true;

字符串
或者,如果您想包含它,则需要将其转换为jsonb,

SELECT 
      p.id,
      p.shop_id,
      p.provider_id,
      p.name,
      p.status,      
      c.product_options::jsonb      
FROM product p      
left join lateral (
  select json_agg(json_build_object(
    'id', po.id,
    'p_id', po.p_id,
    'name', po.name
  )) AS product_options      
  from product_options po        
  where p.id = po.p_id        
  ) c on true
group by p.id, c.product_options::jsonb

相关问题