2016-10-28 71 views
0

我有一个表product,列product_image_path。这些数据部分需要移动到相关表image,该表有一个单独的列image_path和代理键id。这些表通过外键product.image_id相关。有没有办法将product_image_path的所有值插入到image表中,并立即更新product.image_id以引用刚刚创建的行?PostgreSQL:将列提取到单独的表中并使用相关密钥更新其他列

这必须在SQL或PL/pgSQL中完成,因为它是一系列数据库迁移的一部分,不允许任意编写脚本。

product: 
id | product_image_path  
----+------------------- 
    1 | foo.jpg 
    2 | bar.jpg 
    3 | foo.jpg 

应该改为:

product: 
id | image_id 
---+--------- 
1 | 1 
2 | 2 
3 | 3 

image: 
id | image_path 
---+----------- 
1 | foo.jpg 
2 | bar.jpg 
3 | foo.jpg 
+1

添加一些样本表数据,在版本之前和之后。 (以及格式化文本。) – jarlh

+0

@jarlh我现在已经添加了一些示例数据。 – amoe

回答

1

如果新的图片ID可以是相同的产品ID,这是很简单的:

创建新表:

create table image (id serial primary key, image_path text); 

复制产品表中的数据:

insert into image (id, image_path) 
select id, product_image_path 
from product; 

调整为image.id列的顺序:

select setval(pg_get_serial_sequence('image', 'id'), (select max(id) from image)); 

添加新image_id列,并填充它:

alter table product add image_id integer; 
update product set image_id = id; 

摆脱old_column的:

alter table product drop product_image_path; 
相关问题