我正在构建一个简单的图书馆应用程序。我有一个名为books的表,其中包含以下列:
books:
book_id | integer | not null default nextval('books_book_id_seq'::regclass)
title | text | not null
author | text | not null default 'unknown'::text
我原本没有计划对作者做任何特别的处理,因为我只关心他们的名字(所以没有联结表、作者表等)。但是现在,我发现按作者查找书籍的API端点需要某种作者ID:
/browse/author/12345
替代
/browse/author/Arthur%20C%20Clarke (or whatever)
我为作者创建了一个单独的表:
authors:
author_id | integer | not null default nextval('authors_author_id_seq'::regclass)
author_name | text | not null
需要通过id列将每一本书的行与其作者关联起来。我知道我需要一个外键,但由于books表中没有数据,我不能简单地插入一个(所有值都为null等),而且无论如何,我仍然需要获取所有作者id并将它们插入到正确的行中。
如何根据匹配现有列中的值将正确的作者id插入到books表中?我尝试过:
insert into books (author_id) select author_id from authors where (books.author == authors.author_name);
但可以预料的是,那太天真了。