请帮助我理解,如何从一个表中复制值并将其插入到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;
答案 0 :(得分:1)
您需要使用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
答案 1 :(得分:0)
像这样的东西。虽然我不确定你是如何使用斜线" \"。
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;