仅当id不存在时才插入数据库

问题描述 投票:1回答:2

我正在使用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;
sql json database postgresql sql-insert
2个回答
0
投票

id上定义唯一约束:

alter table t add constraint unq_json_table_id unique(id);

然后您可以使用on conflict插入:

insert into json_table . . .
     . . . 
     on conflict (id) do nothing;

0
投票

您可以使用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;

Demo on DB Fiddle

说此记录之前插入过:

insert into json_table(id) values(1)

上面的查询执行没有错误,并且仅插入第二行。

© www.soinside.com 2019 - 2024. All rights reserved.