Ale*_*ber 3 postgresql json plpgsql postgresql-json postgresql-9.5
在 PostgreSQL 9.5 表中,我有一integer列social。
当我尝试在存储过程中更新它时,在in_userstype 变量中给出以下 JSON 数据(一个包含 2 个对象的数组,每个对象都有一个“社交”键)jsonb:
Run Code Online (Sandbox Code Playgroud)'[{"sid":"12345284239407942","auth":"ddddc1808197a1161bc22dc307accccc",**"social":3**,"given":"Alexander1","family":"Farber","photo":"https:\/\/graph.facebook.com\/1015428423940942\/picture?type=large","place":"Bochum, Germany","female":0,"stamp":1450102770}, {"sid":"54321284239407942","auth":"ddddc1808197a1161bc22dc307abbbbb",**"social":4**,"given":"Alxander2","family":"Farber","photo":null,"place":"Bochum, Germany","female":0,"stamp":1450102800}]'::jsonb
然后以下代码失败:
FOR t IN SELECT * FROM JSONB_ARRAY_ELEMENTS(in_users)
LOOP
UPDATE words_social SET
social = t->'social',
WHERE sid = t->>'sid';
END LOOP;
Run Code Online (Sandbox Code Playgroud)
带有错误消息:
ERROR: column "social" is of type integer but expression is of type jsonb
LINE 3: social = t->'social',
^
HINT: You will need to rewrite or cast the expression.
Run Code Online (Sandbox Code Playgroud)
我曾尝试将该行更改为:
social = t->'social'::int,
Run Code Online (Sandbox Code Playgroud)
但后来我得到了错误:
ERROR: invalid input syntax for integer: "social"
LINE 3: social = t->'social'::int,
^
Run Code Online (Sandbox Code Playgroud)
为什么 PostgreSQL 不识别数据是integer?
从JSON-TYPE-MAPPING-TABLE我的印象是 JSON 数字会自动转换为 PostgreSQL 数字类型。
一个基于集合的 SQL 命令比循环更有效:
UPDATE words_social w
SET social = (iu->>'social')::int
FROM JSONB_ARRAY_ELEMENTS(in_users) iu -- in_user = function variable
WHERE w.sid = iu->>'sid'; -- type of sid?
Run Code Online (Sandbox Code Playgroud)
要回答您的原始问题:
为什么 PostgreSQL 不识别数据是整数?
因为您试图将jsonb值转换为integer. 在您的解决方案中,您已经发现您需要->>运算符而不是->提取text,可以将其强制转换为integer。
您的第二次尝试添加了第二个错误:
t->'social'::int
除了上述:operator precedence。cast 运算符的::绑定比 json 运算符强->。就像你已经发现自己一样,你真的想要:
(t->>'social')::int
Run Code Online (Sandbox Code Playgroud)
dba.SE 上的情况非常相似: