根据属性值选择单个 JSON 元素

huangapple go评论61阅读模式
英文:

select a single json element based on a property value

问题

SELECT
  (jsonb_array_elements(tbl.jsonb_column) ->> 'Value') AS result
FROM tbl
WHERE (jsonb_array_elements(tbl.jsonb_column) ->> 'PropertyTypeId')::int = 2;
英文:

I have the following content in a jsonb column:

[
  {
    "Value": "ABC",
    "PropertyTypeId": 1
  },
  {
    "Value": "CDE",
    "PropertyTypeId": 2
  },
  {
    "Value": "FGE",
    "PropertyTypeId": 3
  }
]

And I want to get the value of the element that has a property type of 2 for example.

I've gotten as closes as the following:

SELECT
jsonb_array_elements(tbl.jsonb_column)@>'{"PropertyTypeId": 2}'
FROM tbl

Above only tells me that weather the json contains "PropertyTypeId": 2 or not and it duplicates the rows to 3 rows, I only need one row with the "CDE" in the column.

答案1

得分: 0

可以使用 JSON 路径查询:

    select jsonb_path_query_first(other_properties, '$[*] ? (@.PropertyTypeId == 2)')
    from the_table
英文:

You can use a JSON path query:

select jsonb_path_query_first(other_properties, '$[*] ? (@.PropertyTypeId == 2)')
from the_table

huangapple
  • 本文由 发表于 2023年3月9日 22:11:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685760.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定