如何使用 SQL 删除字符串复制?
How to remove string replication with SQL?
我创建了一个 table,其中 author
字段作为 字符串 ,但后来我意识到应该有另一个 table作者应该是指向 table.
的外键
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
table移动到author
,到目前为止我已经写了这个:
ALTER TABLE post ADD COLUMN author_id;
INSERT INTO author (name) SELECT author FROM post;
但是如何使 post.author_id
指向 author
table 中的正确行?我试过这个:
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 完全相同的结果。
我哪里错了?你能给我指出正确的方法吗?
在 Postgres 中,您不需要明确的 join
。也就是说,您只想提及 post
table 一次:
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
我创建了一个 table,其中 author
字段作为 字符串 ,但后来我意识到应该有另一个 table作者应该是指向 table.
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
table移动到author
,到目前为止我已经写了这个:
ALTER TABLE post ADD COLUMN author_id;
INSERT INTO author (name) SELECT author FROM post;
但是如何使 post.author_id
指向 author
table 中的正确行?我试过这个:
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 完全相同的结果。
我哪里错了?你能给我指出正确的方法吗?
在 Postgres 中,您不需要明确的 join
。也就是说,您只想提及 post
table 一次:
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