为什么这不起作用?基本上,此proc将更新主买方表中的列,以检查用户是否在其他表中有数据。
DO language plpgsql $$
DECLARE
buyer integer;
BEGIN
FOR buyer IN SELECT id FROM buyers
LOOP
IF (SELECT count(*) FROM invoice WHERE buyer_id = buyer) > 0 THEN
UPDATE buyers SET has_invoice = true WHERE id = buyer;
ELSE
UPDATE buyers SET has_invoice = false WHERE id = buyer;
END IF;
END LOOP;
RETURN;
END;
$$;
答案 0 :(得分:1)
目前尚不清楚什么是“不工作”。无论哪种方式,请使用此等效UPDATE
语句:
UPDATE buyers b
SET has_invoice = EXISTS (SELECT 1 id FROM invoice WHERE buyer_id = b.id);
如果您不需要冗余存储来提高性能,可以使用VIEW
或生成的列来实现相同目的。然后,列has_invoice
即时计算并始终保持最新。这个密切相关答案的说明:
Store common query as column?