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

时间:2016-01-19 04:51:03

标签: 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)
)

作者表有所有作者,但现在我正在尝试填充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)
  */

)

2 个答案:

答案 0 :(得分:7)

INSERT语句可以使用SELECT语句返回的行作为插入数据的源。因此,从SELECTposts_temp构建相应的authors语句,然后就完成了:

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

答案 1 :(得分:-1)

DECLARE @InsertedIds TABLE(AID BIGINT) 插入作者(身份证,姓名,专业)                     OUTPUT INSERTED.Id INTO @InsertedIds                     SELECT @ Id,@ name,@ professional

INSERT INTO帖子(id,text,author_id)                     SELECT @ Id,@ text,AID FROM @InsertedIds