Sql 从另一个表获取ID后插入到表中

Sql 从另一个表获取ID后插入到表中,sql,postgresql,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) ) authors表包含所有作者,但现在我正在尝试填充posts表,我有一组数据,基本上有一篇带有作者姓名的文章,但我想查询aut

给出以下两个示例表:

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)
)
authors表包含所有作者,但现在我正在尝试填充posts表,我有一组数据,基本上有一篇带有作者姓名的文章,但我想查询author_id,以便可以按如下方式插入quotes表:

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)
  */

)

INSERT
语句可以使用
SELECT
语句返回的行作为插入数据的源。因此,从
posts\u temp
authors
中构造适当的
SELECT
语句,然后完成以下操作:

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

声明@InsertedIds表(AID BIGINT) 插入作者(Id、姓名、职业) 将输出INSERTED.Id插入@InsertedIds 选择@Id、@name、@profession

插入帖子(id、文本、作者id)
选择@Id、@text、来自@InsertedIds的帮助

效果很好!谢谢你的指导!这对Postgres无效。