在 Postgres 中,可以通过使用子查询检索每行所需的值来对表行执行更新。实现此目的的一种方法是通过以下语法:
UPDATE table_name SET column_name = (SELECT value FROM subquery WHERE subquery_condition) WHERE table_condition;
考虑以下示例,其中目标是更新 Postgres 8.4 数据库中的虚拟表,填写客户、供应商和合作伙伴列使用从子查询派生的值:
CREATE TABLE public.dummy ( address_id SERIAL, addr1 character(40), addr2 character(40), city character(25), state character(2), zip character(5), customer boolean, supplier boolean, partner boolean ) WITH ( OIDS=FALSE ); UPDATE dummy SET customer = (SELECT CASE WHEN cust.addr1 IS NOT NULL THEN TRUE ELSE FALSE END), supplier = (SELECT CASE WHEN suppl.addr1 IS NOT NULL THEN TRUE ELSE FALSE END), partner = (SELECT CASE WHEN partn.addr1 IS NOT NULL THEN TRUE ELSE FALSE END) FROM ( SELECT * FROM address) pa LEFT OUTER JOIN cust_original cust ON (pa.addr1=cust.addr1 AND pa.addr2=cust.addr2 AND pa.city=cust.city AND pa.state=cust.state AND SUBSTR(cust.zip,1,5) = pa.zip ) LEFT OUTER JOIN supp_original suppl ON (pa.addr1=suppl.addr1 AND pa.addr2=suppl.addr2 AND pa.city=suppl.city AND pa.state=suppl.state AND pa.zip = SUBSTR(suppl.zip,1,5)) LEFT OUTER JOIN partner_original partn ON (pa.addr1=partn.addr1 AND pa.addr2=partn.addr2 AND pa.city=partn.city AND pa.state=partn.state AND pa.zip = SUBSTR(partn.zip,1,5) ) WHERE pa.address_id = address_id;
此查询有效更新虚拟表中每行的客户、供应商和合作伙伴列,设置如果在 cust_original、supp_original 和partner_original 表中找到相应的地址,则它们为 TRUE,否则为 FALSE。
此语法不是标准 SQL,但为基于子查询派生的值更新表行提供了便利,特别是在 Postgres 中。
以上是如何使用子查询更新 Postgres 表行?的详细内容。更多信息请关注PHP中文网其他相关文章!