同じテーブルを複数回結合する必要があり、唯一の接続は更新されたテーブル自体であるため、これは私が最初に考えたよりも注意が必要です。
UPDATE table_a a
SET owner1_surname = b1.owner_surname
,owner1_othername = b1.owner_othername
,owner2_surname = b2.owner_surname
,owner2_othername = b2.owner_othername
,owner3_surname = b3.owner_surname
,owner3_othername = b3.owner_othername
FROM table_a x
LEFT JOIN owners_distinct b1 ON b1.b.owner = x.owner1
LEFT JOIN owners_distinct b2 ON b2.b.owner = x.owner2
LEFT JOIN owners_distinct b2 ON b3.b.owner = x.owner3
WHERE x.table_a_id = a.table_a_id
table_a_id
の主キーはどこにありますかtable_a
。通常、テーブルをもう一度結合する必要はありませんが、この状況では、更新されたテーブルにリンクする前に、結合のためにテーブルを結合する必要があります。
LEFT JOIN
3つの所有者のいずれかがで見つからない場合に行の更新全体が失敗するのを防ぐために、を使用しowners_distinct
ます。
データベース設計
のすべての冗長データが必要table_a
ですか?正規化されたスキーマの標準的な方法は、 foreign keys
(owner1
、、 )のみを格納しowner2
、owner3
オンデマンドで名前の詳細を取得JOIN
することSELECT
です。更新する列をすべて削除します。もちろん、ルールには常に例外があります...
一意のキーはありませんか?
これはそもそも起こるべきではありません。次のような代理主キーを追加する必要があります。
ALTER TABLE table_a ADD table_a_id serial PRIMARY KEY;
これについては、関連する回答を
参照してください。テーブルに主キーが必要ですか。これには、UNIQUE(複合4列)があり、そのうちの1つはNULLにすることができますか?
一意のキーのないソリューション
とにかく、一意の列に関係なく、この更新を行う方法は次のとおりです。
UPDATE table_a a
SET owner1_surname = b1.owner_surname
,owner1_othername = b1.owner_othername
,owner2_surname = b2.owner_surname
,owner2_othername = b2.owner_othername
,owner3_surname = b3.owner_surname
,owner3_othername = b3.owner_othername
FROM (SELECT DISTINCT owner1, owner2, owner3 FROM table_a) x
LEFT JOIN owners_distinct b1 ON b1.b.owner = x.owner1
LEFT JOIN owners_distinct b2 ON b2.b.owner = x.owner2
LEFT JOIN owners_distinct b2 ON b3.b.owner = x.owner3
WHERE x.owner1 = a.owner1
AND x.owner2 = a.owner2
AND x.owner3 = a.owner3;
重要なのは、それぞれの組み合わせを(owner1, owner2, owner3)
1回だけ必要とするということです。