Dalam PostgreSQL, mengemas kini baris sedia ada menggunakan nilai yang dikembalikan daripada pernyataan SELECT boleh dicapai melalui sintaks yang mudah.
Pertimbangkan jadual yang disediakan skema:
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 );
Untuk mengemas kini jadual berdasarkan subkueri, gunakan sintaks berikut:
UPDATE dummy SET customer = subquery.customer, address = subquery.address, partn = subquery.partn FROM ( SELECT address_id, customer, address, partn FROM /* big hairy SQL */ ... ) AS subquery WHERE dummy.address_id = subquery.address_id;
Sintaks ini bukan SQL standard tetapi sesuai untuk jenis pertanyaan ini. Contohnya, untuk mengemas kini pelanggan, alamat dan lajur bahagian berdasarkan hasil gabungan kompleks, anda boleh menggunakan subkueri berikut:
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 address, CASE WHEN partn.addr1 IS NOT NULL THEN TRUE ELSE FALSE END AS partn FROM ( SELECT * FROM address ) 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;
Dengan melaksanakan kemas kini ini, lajur yang ditentukan dalam jadual tiruan akan dikemas kini dengan nilai yang diperoleh daripada subkueri.
Atas ialah kandungan terperinci Bagaimanakah Saya Boleh Kemas Kini Baris Jadual PostgreSQL Menggunakan Subkueri?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!