【问题标题】:How to remove string replication with SQL?如何使用 SQL 删除字符串复制?
【发布时间】:2021-05-16 10:39:24
【问题描述】:

我创建了一个带有author 字段作为字符串 的表,但后来我意识到应该有另一个表,并且作者应该是指向该表的外键。

CREATE TABLE post (
  id SERIAL INT NOT NULL PRIMARY KEY,
  author VARCHAR(80) NOT NULL
)

CREATE TABLE author (
  id SERIAL INT NOT NULL PRIMARY KEY,
  name VARCHAR(80) NOT NULL
)

现在,我很好奇如何将作者数据从post 表移动到author,到目前为止我已经写了这个:

ALTER TABLE post ADD COLUMN author_id;
INSERT INTO author (name) SELECT author FROM post;

但是如何使post.author_id 指向author 表中的正确行?我试过这个:

update post
set author_id = author.id
from post p
inner join author
on p.author = author.name;

根据this 问题,但在执行之后post 中的所有行现在都指向author 1!然后我想我必须添加 where 子句:

update post
set author_id = author.id
from post p
inner join author
on p.author = author.name
where author.name = p.author; 

但这又产生了前一个 SQL 的确切结果。

我哪里出错了?能否请您指出正确的方法。

【问题讨论】:

    标签: sql postgresql sql-update


    【解决方案1】:

    在 Postgres 中,您不需要明确的 join。也就是说,您只想提及post 表一次:

    update post p
        set author_id = a.id
    from author a
    where p.author = a.name;
    

    post 的多次提及是单独的,这意味着查询正在执行:

    post cross join
    post p join
    author a
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      • 2010-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-01
      • 2021-07-04
      相关资源
      最近更新 更多