基于子查询的唯一值的postgres规则更新字段

时间:2013-01-24 06:38:18

标签: sql database postgresql

当我用实际值替换id_sitio时,我能够更新基于子查询的字段:

update sitios
set grado = (
    select count(lin_sit.id_lineamiento) as total
    from lineamientos_sitios lin_sit inner join sitios sit on lin_sit.id_sitio=sit.id_sitio
    where sit.id_sitio=1418
)
where id_sitio=1418;

但是当我实施规则时却没有。

CREATE or replace RULE actualizar_lineamientos_sitios_view AS ON UPDATE TO lineamientos_sitios_view DO INSTEAD (
UPDATE lineamientos_sitios SET id_lineamiento = new.id_lineamiento, id_sitio = new.id_sitio WHERE (lineamientos_sitios.id_lineamiento = old.id_lineamiento AND lineamientos_sitios.id_sitio = old.id_sitio);
update sitios  set grado = (select count(lin_sit.id_lineamiento) as total from lineamientos_sitios lin_sit inner join sitios sit on lin_sit.id_sitio=sit.id_sitio where sit.id_sitio=new.id_sitio) where id_sitio=new.id_sitio;
);

我认为第一次更新无关紧要,因为它有效,我不确定如何从我想上传的记录中引用id

任何解决方案?谢谢!

1 个答案:

答案 0 :(得分:1)

嗨克雷格(欢迎其他人;)

非常感谢你。你让我知道了,但是删除规则有些麻烦。第一个规则工作正常,所以我可以在子查询中上传字段grado。但计算Grado2_view规则不能使工作..

CREATE RULE calcularGrado_view AS ON INSERT TO lineamientos_sitios_view DO INSTEAD (

update sitios  set grado = (select count(lin_sit.id_lineamiento) as total from lineamientos_sitios lin_sit inner join sitios sit on lin_sit.id_sitio=sit.id_sitio where sit.id_sitio=new.id_sitio) where id_sitio=new.id_sitio;

);

CREATE RULE calcularGrado2_view AS ON DELETE TO lineamientos_sitios_view DO INSTEAD (

update sitios  set grado = (select count(lin_sit.id_lineamiento) as total from lineamientos_sitios lin_sit inner join sitios sit on lin_sit.id_sitio=sit.id_sitio where sit.id_sitio=old.id_sitio) where id_sitio=old.id_sitio;

);

你知道规则有什么问题吗? 谢谢!