简而言之,我正在努力做到这一点:

设置:

create table info(
  info_id serial primary key, 
  info_text text
);
create table product(
  prod_id serial primary key, 
  info_id int /*unique*/, 
  description text unique, 
  price int);

insert into product (description, price) values ('pen', 1), ('notebook', 2), ('ruller', 3);

现在,我try 更新info_id引用为null的所有product行,方法是在info表中创建一个新行,然后将对它的引用分配给产品:

with new_info as (insert into info default values returning info_id)
update product
set info_id = (select info_id from new_info)
where product.info_id is null;

The problem is that it only creates one info and then assigns all products to it. I expect it to create one companion info row for each product.

select * from product, info where product.info_id = info.info_id;
 prod_id | info_id | description | price | info_id | info_text 
---------+---------+-------------+-------+---------+-----------
       1 |       1 | pen         |     1 |       1 | [null]
       2 |       1 | notebook    |     2 |       1 | [null]
       3 |       1 | ruller      |     3 |       1 | [null]

推荐答案

这将在表info中创建单独的新行,并为product.info_id中的每个空值回填对该行的引用:

WITH upd AS (
   UPDATE product
   SET    info_id = nextval(pg_get_serial_sequence('info', 'info_id'))
   WHERE  info_id IS NULL
   RETURNING info_id
   )
INSERT INTO info (info_id)
SELECT info_id
FROM   upd;

fiddle

甚至可以与适当的FK约束一起使用.

相关:

Sql相关问答推荐

如何查询一个名称是根据PL/pgSQL函数结果构建的表?

为什么postgres中CURRENT_TIMESTAMP的日期与CURRENT_DATE不同?

当我们加入两个表时,我们可以省略GROUP BY中的列名吗?

Android房间fts4匹配语法AND OR

如何隐藏聚合JSON数组元素的键

数据库SQL-CTE命名空间(错误?)使用临时视图

在xml.Modify方法中使用子字符串和可能的替代方法

基于另一个(SAS、SQL)中的值更新列

从重复值中获取最新值

STContains、STIntersections和STWithin返回错误的地理结果

将具有嵌套 XML 的列转换为 SQL 中的表格格式?

如何在Hive SQL中分别按多列进行分组?

SQL 搜索 - 获取最大值日期的奇怪行为

SQL 语句将一列中的值与另一列中的不同值相加,同时按第三列进行分组?

Oracle PL/SQL长期运行问题

如何创建一个递归计数器来查找一个元素有多少父级和子级?

COBOL\DB2作业(job)需要帮助?快来获取专业指导!

使用其他表 SUM 的交换价格转换价格并获得 AVG

SQLite 中的过滤运行总和视图

如何使用子查询锁定此查询中的选定行?