select id,rules from links where id=2;
id | rules
----+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2 | {"{\"id\": \"61979e81-823b-419b-a577-e2acb34a2f40\", \"url\": \"https://www.wikijob.co.uk/about-us\", \"what\": \"country\", \"matches\": \"GB\", \"percentage\": null}"}
我正在尝试使用此处的https://www.postgresql.org/docs/9.6/functions-json.html
运算符来获取jsonb的元素无论我使用“ url”还是下面的整数,我都会得到类似的结果。
select id,rules->1 from links where id=2;
ERROR: operator does not exist: jsonb[] -> integer
LINE 1: select id,rules->1 from links where id=2;
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
我在做什么错?
PS Postgres版本9.6.12。
答案 0 :(得分:1)
该列是一个数组,您可以使用索引访问第一个元素:
select id, rules[1]
from links
where id = 2
请务必同时检查this answer.
在横向联接中使用jsonb_each()
可以在单独的行中查看所有规则:
select id, key, value
from links
cross join jsonb_each(rules[1]) as rule(key, value)
where id = 2
您可以通过以下方式获得一条规则:
select id, value as url
from links
cross join jsonb_each(rules[1]) as rule(key, value)
where id = 2 and key = 'url'
使用unnest()
在数组的所有元素中查找url
,例如:
select id, unnest(rules)->'url' as url
from links
where id = 2;