我正在使用Postgres,在下面的代码中,我仅想在数据库id
不存在时才插入数据库。
DROP TABLE json_table;
CREATE temp TABLE json_table (
id VARCHAR(50) PRIMARY KEY,
str_col VARCHAR(500),
int_col SMALLINT,
bool_col BOOLEAN,
json_col JSON,
float_col DECIMAL
);
INSERT INTO json_table
SELECT * FROM json_populate_recordset (NULL::json_table,
'{ "insert": [
{
"id": "1",
"str_col": "Postgres bar data",
"int_col": 3151,
"bool_col": false,
"json_col": {
"data": "tutorials"
},
"float_col": 11.51099159756918
},
{
"id": "2",
"str_col": "Postgres tutorials data data",
"int_col": 4237,
"bool_col": true,
"json_col": {
"type": "type"
},
"float_col": 48.94065780742467
}
]}'::json->'insert');
SELECT * FROM json_table;
您可以使用该on conflict do nothing
子句。您的id
列是表的主键,因此可以正常工作:
INSERT INTO json_table
SELECT *
FROM json_populate_recordset (NULL::json_table,
'{ "insert": [
{
"id": "1",
"str_col": "Postgres bar data",
"int_col": 3151,
"bool_col": false,
"json_col": {
"data": "tutorials"
},
"float_col": 11.51099159756918
},
{
"id": "2",
"str_col": "Postgres tutorials data data",
"int_col": 4237,
"bool_col": true,
"json_col": {
"type": "type"
},
"float_col": 48.94065780742467
}
]}'::json->'insert')
ON CONFLICT (id) DO NOTHING;
假设此记录已插入:
insert into json_table(id) values(1)
上面的查询没有错误地执行,并且仅插入第二行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句