请帮助我理解,如何从一个表中复制值并将其插入到jsonb字段中的另一个表中?
additional_info
是产品表中的jsonb字段。
dedication, stories, status
这个字段来自书籍表我想在additional_info
字段中复制。
我试过这样,但显然这是不正确的
INSERT INTO products (order_id, name, price, type, additional_info)
SELECT order_id, name, null, 'Book', '{\"dedication\": dedication, \"stories\": stories, \"status\": status }'
FROM books;
你需要使用jsonb_build_object
。 \
在SQL中没有特殊含义,在SQL字符串文字中不需要\"
:
INSERT INTO products (order_id, name, price, type, additional_info)
select order_id,
name,
null,
'Book',
jsonb_build_object('dedication', dedication, 'stories', stories, 'status', status)
from books
像这样的东西。虽然我不确定你是如何使用斜杠“\”的。
INSERT INTO products (order_id, name, price, type, additional_info)
SELECT order_id, name, null, 'Book', json_build_object("dedication\", dedication, "stories\", stories, "status\", status) AS additional_info
FROM books;