假设我有一个名为 users
的表,其中包含名为 attrs
的 jsonb
列,其值如下:
{
"uuid5": {
"label": "Email",
"value": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="debba6bfb3aeb2bb9eaabbadaaf0bdb1b3f0aaa9" rel="noreferrer noopener nofollow">[email protected]</a>"
},
"uuid6": {
"label": "Last Name ",
"value": "Yang"
}
}
这里有一句台词:
"attrs": { "uuid5": { "label": "Email", "value": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="305548515d405c5570445543441e535f5d1e4447" rel="noreferrer noopener nofollow">[email protected]</a>" }, "uuid6": { "label": "Last Name ", "value": "Yang" }
如您所见,有 uniq 键 uuid5
、uuid6
等。
如何获取标签 = 'Email' 且值 = ' [email protected] 的用户'?
在 postgres docs
关于 json 函数,有一个名为 jsonb_each
的函数它返回一组 JSON 对象键/值对。但我找不到基于此编写查询的方法。
最佳答案
您需要 jsonb_each
来迭代 attrs 列中的所有条目。它将返回键/值对,其中键是 uuid,条目是您要检查的实际 JSON 结构。您可以将其与 EXISTS 条件结合使用:
select u.*
from users u
where exists (select *
from jsonb_each(u.attrs) as t(uid,entry)
where t.entry ->> 'label' = 'Email'
and t.entry ->> 'value' = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92f7eaf3ffe2fef7d2e6f7e1e6bcf1fdffbce6e5" rel="noreferrer noopener nofollow">[email protected]</a>')
关于json - 如何在postgres中查询嵌套json中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55512016/