如何解决从一个表中提取一列到另一个表中,并将插入的行的ID作为外键存储PostgreSQL
按照我们当前的系统状态,我们有一个表( ExistingEntity ),其中包含一列( type )
作为结构更改的一部分,需要将该值“提取”到新表(属性)中的一行,并将新行的ID作为外键存储在 ExistingEntity.properties 。 Properties.id 是一个自动递增的序列。
所以我需要做什么:
- 将
e.type
中的ExistingEntity e
插入Properties p
- 将
e.properties
设置为p.id
我将如何进行查询?我们的数据库使用的是PostgreSQL 9.6
编辑: 似乎我的解释对于某些人来说似乎有点含糊不清,我想完成的是两个表
ExistingEntity
+------+------+
| id | type |
+------+------+
| 1735 | 4 |
| ... | ... |
+------+------+
Type
+-----+---------------------+
| id | data |
+-----+---------------------+
| 4 | "imageSomeDataHere" |
| ... | ... |
+-----+---------------------+
被提取到三个表中
ExistingEntity
+------+------------+
| id | properties |
+------+------------+
| 1735 | 1 |
| ... | ... |
+------+------------+
Properties
+-----+------+
| id | type |
+-----+------+
| 1 | 4 |
| ... | ... |
+-----+------+
Type
+-----+---------------------+
| id | data |
+-----+---------------------+
| 4 | "imageSomeDataHere" |
| ... | ... |
+-----+---------------------+
我认为查询
UPDATE ExistingEntity e SET properties = (
INSERT INTO Properties (type) VALUES (e.type) RETURNING id
);
可以工作,但是IntelliJ抱怨那个语法
解决方法
在这里使用有利于您的事务并按顺序执行的事实。 DDL代码可能无法完全正常工作,因为我在手机上,但是应该很容易找到它。
BEGIN TRANSACTION;
CREATE TABLE Properties...; -- id and type columns,and a temporary entity_id
-- Properties.Id should auto-increment
INSERT INTO Properties(entity_id,type)
SELECT id,type
FROM ExistingEntity;
-- Make property NULLABLE for now
ALTER TABLE ExistingEntity DROP COLUMN type;
ALTER TABLE ExistingEntity ADD COLUMN property NULL;
-- Connect ExistingEntity to Properties
UPDATE ExistingEntity
SET property = Properties.id
FROM Properties
WHERE Properties.entity_id = ExistingEntity.id;
-- Cleanup
ALTER TABLE Properties DROP COLUMN entity_id;
ALTER TABLE ExistingEntity ALTER COLUMN property NON NULL;
-- Finally,commit
COMMIT;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。