使用子查询更新 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中文网其他相关文章!