在 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中文網其他相關文章!