是否可以比较jsonb中的不同字段

问题描述

列类型为 jsonb 的表。

此处json

"weight": {
    "qty": 1112,"unit": {
      "name": "gram"
    }
  },"options": [
    {
      "name": "genus_species","value": {
        "name": "cucumber"
      }
    },{
      "name": "weight","value": {
        "name": "600g"
      }
    },{
      "name": "method","value": {
        "name": "salt"
        }
      }
    },{
      "name": "tm","value": {
        "name": "chudova-marka"
      }
    }
  ]

在此示例中,值“ 1112 ”的“ weight.qty ”不等于“ value.name.600g ”。因此,此记录将返回

P.S。我将“ 数量”转换为字符串,并添加后缀“ g ”以作为字符串进行比较。

所以这里查询没有比较

SELECT 
concat(product.data->'weight'->>'qty','g') AS weight,product.data #>>'{options,value,name}' as n1,1,name}' as n2,2,name}' as n3,3,name}' as n4
FROM product

我需要显示 weight.qty ”不等于任何“ options.value.name ”的记录。 有可能吗?

解决方法

您需要取消嵌套数组元素:

select p.*
from product p
where not exists (select * 
                  from jsonb_array_elements(p.data -> 'options') as x(option)
                  where x.option ->> 'name' = 'weight' 
                    and x.option -> 'value' ->> 'name' = concat(p.data->'weight'->>'qty','g'))