如何更改某些表行的id?
喜欢:
UPDATE table SET id=10 WHERE id=5;
但是,它会将更改级联到每个引用此表的其他表的更改?
我想这样做,因为我需要从具有大多数相同表的另一个数据库导入数据,但是ID不同.因此,如果id与旧数据库匹配,则更容易正确导入数据.
假设你有这两个表:
原文链接:https://www.f2er.com/postgresql/191952.htmlcreate table referenced (id integer primary key); create table referencer (a integer references referenced (id));
引用的表引用器引用表:
=> \d referencer Table "public.referencer" Column | Type | Modifiers --------+---------+----------- a | integer | Foreign-key constraints: "referencer_a_fkey" FOREIGN KEY (a) REFERENCES referenced(id)
然后在两者中插入一个值:
insert into referenced values (1); insert into referencer values (1); select * from referenced rd inner join referencer rr on rd.id = rr.a ; id | a ----+--- 1 | 1
现在您要更改对更新级联的引用:
alter table referencer drop constraint referencer_a_fkey,add foreign key (a) references referenced (id) on update cascade;
并更新它:
update referenced set id = 2; select * from referenced rd inner join referencer rr on rd.id = rr.a ; id | a ----+--- 2 | 2
现在,如果已更新的ID已存在,则在引用的表主键中将出现另一个问题.但这会产生另一个问题.
UPDATE
update pg_constraint set confupdtype = 'c' where conname in ( select c.conname from pg_constraint c inner join pg_class referenced on referenced.oid = c.confrelid where referenced.relname = 'referenced' and c.contype = 'f' );
它会将引用表上的所有外键约束更改为更新级联