一个简单的 pg/plsql 循环示例
我们正在重新设计 postgres 中的表架构。它曾经有一个链接器表,指向名为 partner_advertiser
的两个表 partner
和 advertiser
,因为我们假设合作伙伴之间存在多对多关系和广告商。进行了一项更改,使得广告商
只能拥有一个合作伙伴
,因此合作伙伴
将与广告商<具有一对一的关系/代码>。
如何进行更改而不丢失以前的信息?链接器表数据必须用于填充新模式设计的映射。 这是我的初始代码:
BEGIN
FOR r IN SELECT partnerid, advertiserid from partner_advertiser
LOOP
NEXT r;
UPDATE advertiser SET partnerid = r.partnerid WHERE id = r.advertiserid
END LOOP;
END
顺便说一句,我自己没有做过任何 pg/plsql。因此,如果我应该采取任何基本步骤,请提前告知我。
We are redesigning table schema in postgres. It used to have a linker table to the two tables partner
and advertiser
of the name partner_advertiser
since we were assuming a many-many relationship between partner and advertiser. A change is made such that an advertiser
shall have only one partner
, so partner
will have a one-may relationship to advertiser
.
How do I make the change without losing previous information? The linker table data must be used to fill in the mapping of the new schema design.
Here is my initial code:
BEGIN
FOR r IN SELECT partnerid, advertiserid from partner_advertiser
LOOP
NEXT r;
UPDATE advertiser SET partnerid = r.partnerid WHERE id = r.advertiserid
END LOOP;
END
BTW I haven't done any pg/plsql myself. So if there are any basic steps I should make please give me a heads-up.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用:
一般来说,像这样的简单关系转换永远不需要循环。
不过,如果您确实需要一个,请查看 http://www.postgresql.org/ docs/9.0/interactive/plpgsql-control-structs.html
一个额外的注意事项:如果advertiserid还不是唯一的,任何转换显然都会丢失数据,因此您应该首先运行类似的命令
如果返回任何行,您将想手动修复这个问题。
You can use:
Generally, simple relational transformations like these will never need a loop.
If you really need one, though, look at http://www.postgresql.org/docs/9.0/interactive/plpgsql-control-structures.html
One extra note: any transformation will obviously lose data if advertiserid is not already unique, thus you should first run something like
If any rows get returned by that you will want to fix that manually.
这也有效。使用一个简单的
plpgsql
片段:This also works. Using a simple
plpgsql
snippet: