Postgresql

如何插入包含外鍵的行?

  • August 18, 2020

使用 PostgreSQL v9.1。我有以下表格:

CREATE TABLE foo
(
   id BIGSERIAL     NOT NULL UNIQUE PRIMARY KEY,
   type VARCHAR(60) NOT NULL UNIQUE
);

CREATE TABLE bar
(
   id BIGSERIAL NOT NULL UNIQUE PRIMARY KEY,
   description VARCHAR(40) NOT NULL UNIQUE,
   foo_id BIGINT NOT NULL REFERENCES foo ON DELETE RESTRICT
);

假設第一個表foo是這樣填充的:

INSERT INTO foo (type) VALUES
   ( 'red' ),
   ( 'green' ),
   ( 'blue' );

bar有沒有辦法通過引用表輕鬆插入行foo?還是我必須分兩步完成,首先查找foo我想要的類型,然後在 中插入一個新行bar

這是一個虛擬碼範例,顯示了我希望可以完成的操作:

INSERT INTO bar (description, foo_id) VALUES
   ( 'testing',     SELECT id from foo WHERE type='blue' ),
   ( 'another row', SELECT id from foo WHERE type='red'  );

您的語法幾乎很好,需要在子查詢周圍加上一些括號,它會起作用:

INSERT INTO bar (description, foo_id) VALUES
   ( 'testing',     (SELECT id from foo WHERE type='blue') ),
   ( 'another row', (SELECT id from foo WHERE type='red' ) );

DB-Fiddle測試

另一種方法,如果您要插入很多值,則使用更短的語法:

WITH ins (description, type) AS
( VALUES
   ( 'more testing',   'blue') ,
   ( 'yet another row', 'green' )
)  
INSERT INTO bar
  (description, foo_id) 
SELECT 
   ins.description, foo.id
FROM 
 foo JOIN ins
   ON ins.type = foo.type ;

引用自:https://dba.stackexchange.com/questions/46410