使用子查詢更新PostgreSQL 表行
考慮一個場景,您在Postgres 資料庫中有一個現有表,並且需要更新它的行使用從子查詢獲得的值。此任務可以使用簡潔的更新語句來完成。
在這種特殊情況下,目標是使用從連接多個表(cust_original、supp_original 和partner_original)的複雜子查詢檢索到的值來更新虛擬表中的行。 )並應用條件邏輯來決定客戶、供應商和合作夥伴列的值。
要執行此更新,您可以使用以下命令語法:
UPDATE dummy SET customer = subquery.customer, supplier = subquery.supplier, partner = subquery.partner FROM ( SELECT address_id, CASE WHEN cust.addr1 IS NOT NULL THEN TRUE ELSE FALSE END AS customer, CASE WHEN suppl.addr1 IS NOT NULL THEN TRUE ELSE FALSE END AS supplier, CASE WHEN partn.addr1 IS NOT NULL THEN TRUE ELSE FALSE END AS partner FROM address AS pa LEFT OUTER JOIN cust_original AS cust ON (pa.addr1 = cust.addr1 AND pa.addr2 = cust.addr2 AND pa.city = cust.city AND pa.state = cust.state AND SUBSTRING(cust.zip, 1, 5) = pa.zip) LEFT OUTER JOIN supp_original AS suppl ON (pa.addr1 = suppl.addr1 AND pa.addr2 = suppl.addr2 AND pa.city = suppl.city AND pa.state = suppl.state AND pa.zip = SUBSTRING(suppl.zip, 1, 5)) LEFT OUTER JOIN partner_original AS partn ON (pa.addr1 = partn.addr1 AND pa.addr2 = partn.addr2 AND pa.city = partn.city AND pa.state = partn.state AND pa.zip = SUBSTRING(partn.zip, 1, 5)) WHERE pa.address_id = address_id ) AS subquery WHERE dummy.address_id = subquery.address_id;
此語句利用子查詢來派生客戶、供應商和合作夥伴列的值。子查詢執行您提供的插入語句中指定的必要連接和條件邏輯。
外部 UPDATE 語句然後將這些子查詢派生的值套用到虛擬表中的對應列,根據address_id 欄位。
當您需要根據複雜或動態計算派生的值更新表行時,或者在處理傳統逐行更新的大型資料集時,此方法特別有用可能效率低下。
以上是如何使用帶有條件邏輯的子查詢更新 PostgreSQL 表行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!