且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在PostgreSQL中将多对多关系转换为一对多关系

更新时间:2022-11-05 10:27:12

UPDATE bar b
SET    foo_id = fb.foo_id
FROM   foo_bar fb
WHERE  fb.bar_id = b.bar_id;

如果一个栏应该有多个行(你不应该根据你的描述)一行将被更新多次,结果是任意的。

If you should have multiple rows for one bar (which you shouldn't, according to your description) the one row will be updated multiple times and the result is arbitrary.

这种形式的查询通常表现得更好而不是相关的子查询。

This form of the query generally performs better than a correlated subquery.

请注意, bar 的主键应该真的被命名为 bar_id - 我在查询中使用该名称。

Note that the primary key of bar should really be named bar_id - I use that name in the query.