获取不同表SQL中的重复项和更新列

时间:2015-05-01 17:53:35

标签: sql postgresql

我有两张桌子:

诗:

---------------------------------------------------
|  id  |        poem        |        author       |
---------------------------------------------------
|   1  |   Blah blah Hey    |       Jane Doe      |
---------------------------------------------------
|   1  |   Yo yo Hey Bla    |       Jane Doe      |
---------------------------------------------------

作者:

-----------------------------
|  id  |        name        |
-----------------------------
|   0  |                    |
-----------------------------

我想从诗歌表中删除重复项并填充新创建的authors表。理想情况下,我想在author表中使用author.id更新作者(或创建一个新的authors_id)列

我知道以下代码显示我的重复项

SELECT author, COUNT(*) 
FROM poem
GROUP BY author
HAVING
    COUNT(*) > 1

但是如何将它们添加到author.names列?

此外,这段代码会帮助我完成下一部分吗?

ALTER TABLE poem
     ADD COLUMN author_id serial,
     ADD CONSTRAINT author_id FOREIGN KEY (id) REFERENCES author (id) MATCH FULL;

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

尝试从select语句插入。例如:

    insert into Authors (id, author)
    select distinct id, author
    from Poems