有两张桌子:
CREATE TABLE user (
id bigserial,
name varchar(255),
address varchar(255)
)
CREATE TABLE user_history (
id bigserial,
user_id int8
user_json json,
create_date timestamp
)
user.id
由DEFAULT
生成。我想为正在创建的用户创建一个历史记录,但我不知道如何将generated
user.id
传递给json。像这样的:INSERT INTO user_history
VALUES (
DEFAULT,
(SELECT id FROM user WHERE name = 'Some name'),
'{
"id": GENERATED ID HERE,
"name": "Some name",
"address": "Some address"
}',
'2010-01-01 00:00:00'
);
博士后10
最佳答案
在顶部:
with c as (SELECT id FROM user WHERE name = 'Some name')
INSERT INTO user_history (user_id,user_json,create_date)
select id, concat(
'{
"id": ',id,',
"name": "Some name",
"address": "Some address"
}')::json,
'2010-01-01 00:00:00'
from c
;
也可以使用
json_build_object
生成json?..here' working example
更新
我没有重新分析json中的所有键/值都来自用户表,下面是对它的简短查询:
INSERT INTO user_history (user_id,user_json,create_date)
select id, json_build_object('id',id,'name',name,'address',address), '2010-01-01 00:00:00'
from "user"
http://sqlfiddle.com/#!17/19a8e/3
同样,保存user_json也没有多大意义-您可以通过FK在user_history.user_id上获得它
t=# select to_json(u) from "user" u;
to_json
--------------------------------------------
{"id":1,"name":"Some name","address":null}
关于sql - JSON中的PostgreSQL INSERT动态值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47592570/