【问题标题】:PostgreSQL(function) - Implementation of where clause to get rows by a value(concatenate) in the JSONB columnPostgreSQL(函数) - 实现 where 子句通过 JSONB 列中的值(连接)获取行
【发布时间】:2020-09-03 12:40:28
【问题描述】:

我正在尝试从我希望条件检查 jsonb 列中的值的表中获取行。该列将数据存储为:

[{"UserId": 420, "Permission": "Create"}, {"UserId": 369, "Permission": "View"}]

在函数中,我使用以下方法检查值:

tab."Books" @> '[{"UserId":420}]'

但我希望将 420 替换为通过函数传递的“ID”。我遇到的唯一方法是串联(

tab."Books" @> '[{"UserId":'||ID||'}]'

这没有帮助。

我做错了吗?如果有的话,请提出替代方案。谢谢。

【问题讨论】:

    标签: sql arrays json postgresql where-clause


    【解决方案1】:

    你应该可以cast:

    tab."Books" @> ('[{"UserId":' || ID || '}]')::jsonb
    

    或者你可以使用 json builder 函数:

    tab."Books" @> jsonb_build_array(jsonb_build_object('UserId', ID))
    

    【讨论】:

    • 尝试了第一个建议,效果很好。非常感谢!
    【解决方案2】:

    您可以使用jsonb_build_object,然后将其转换为 JSON 数组:

    tab."Books" @> jsonb_build_array(jsonb_build_object('UserId', id))
    

    【讨论】:

      猜你喜欢
      • 2015-07-09
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 2016-03-05
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      相关资源
      最近更新 更多