从另一个表获取ID后插入表

Det*_*ned 3 sql postgresql

给出这两个示例表:

authors(
  id SERIAL PRIMARY KEY,
  name VARCHAR(60) UNIQUE,
  profession VARCHAR(30)
)

posts(
  id SERIAL PRIMARY KEY,
  text TEXT,
  author_id INT REFERENCES authors(id)
)
Run Code Online (Sandbox Code Playgroud)

作者表有所有作者,但现在我正在尝试填充posts表,我有一组数据,基本上有一个带有作者姓名的帖子,但我想查询author_id以便我可以如下插入引号表:

INSERT INTO posts(text, author_id) VALUES(
  /* 
     pseudo broken-code
     SELECT post, author FROM posts_temp (where all of the data temp resides),
     SELECT id FROM authors WHERE authors.name = author.name (obviously this is wrong, but the idea is getting the id from the authors table that matches the author name from the selection above)
  */

)
Run Code Online (Sandbox Code Playgroud)

Pat*_*ick 7

一个INSERT语句可以使用由返回的行SELECT语句作为源插入数据.因此,构建适当SELECT的语句posts_tempauthors,然后你做:

INSERT INTO posts(text, author_id)
  SELECT pt.post, a.id
  FROM posts_temp pt
  JOIN authors a ON a.name = pt.author;
Run Code Online (Sandbox Code Playgroud)