Postgres 在不存在多个值的地方插入

Postgres Insert where not exists multiple values

我想在 Postgres 中插入多个值 table (value, guest_name, guest_room_number, created, employee_id, guest_group_id, table_numbers, show) 如果多个值(value, guestName, guestRoomNumber)不存在。我怎样才能做到这一点?

感谢您的帮助。

我的尝试:

 await this.db.query(
 `INSERT INTO app_trace(value, guest_name, guest_room_number, created, employee_id, guest_group_id, table_numbers, show)
  SELECT , , , , , , , 
  WHERE NOT EXISTS (SELECT value FROM app_trace WHERE value= AND guest_name= AND guest_room_number=)`,
 [value, guestName, guestRoomNumber, created, employeeId, guestGroupId, tableNumbers, show]);`

尝试仍在保存数据,即使值确实存在于数据库中。

数据库中的示例数据:

INSERT INTO "public"."app_trace"("id","value","guest_name","guest_room_number","created","employee_id","guest_group_id","table_numbers","show")
VALUES
(88,E'test',E'Maierei',E'123',E'2019-08-05 15:15:45.984+00',1,65866,E'90',NULL);

这次尝试仍然插入数据,但我不想要那样。

 await this.db.query(
 `INSERT INTO app_trace(value, guest_name, guest_room_number, created, employee_id, guest_group_id, table_numbers, show)
  SELECT , , , , , , , 
  WHERE NOT EXISTS (SELECT value FROM app_trace WHERE value= AND guest_name= AND guest_room_number=)`,
 ['test', 'Maierei', '123', '2019-08-06 15:15:45.984+00', 1, 123445, '23', true]);`

我希望语句不插入数据,因为值(value、guestName、guestRoomNumber)已经存在于 table。

如果您在 value, guest_name, guest_room_number 列中没有唯一约束,您一定要创建一个。之后只需创建一个 upsert 以在发生冲突时忽略插入,例如

INSERT INTO app_trace 
  (value, guest_name, guest_room_number, created, 
   employee_id, guest_group_id, table_numbers, show)
VALUES (, , , , , , , )
ON CONFLICT (value,guest_name,guest_room_number) DO NOTHING

示例:

CREATE TEMPORARY TABLE t (foo INT, bar INT, bar2 INT, PRIMARY KEY (foo,bar));
INSERT INTO t (foo, bar, bar2) VALUES(1, 2, 1) ON CONFLICT (foo,bar) DO NOTHING;
INSERT INTO t (foo, bar, bar2) VALUES(1, 2, 42) ON CONFLICT (foo,bar) DO NOTHING;

SELECT * FROM t;

 foo | bar | bar2 
-----+-----+------
   1 |   2 |    1
(1 Zeile)