2

PostgreSQL(9.1)にpgadminを使用していますが、実行に時間がかかりすぎるこのクエリがあります

update tableA a
set owner1_surname = (select owner_surname from owners_distinct b where a.owner1= b.owner),
owner1_othername   = (select owner_othername from owners_distinct b where a.owner1= b.owner),
owner2_surname     = (select owner_surname from owners_distinct b where a.owner2= b.owner),
owner2_othername   = (select owner_othername from owners_distinct b where a.owner2= b.owner),
owner3_surname     = (select owner_surname from owners_distinct b where a.owner3= b.owner),
owner3_othername   = (select owner_othername from owners_distinct b where a.owner3= b.owner)

何度も何度も値を取得する代わりに、列をowners_distinct table取得し、チェックに基づいての列を一度だけ使用して実行することは可能ですか?ownerowner_surnameowner_othernameSELECTUPDATEtableA

4

2 に答える 2

1

同じテーブルを複数回結合する必要があり、唯一の接続は更新されたテーブル自体であるため、これは私が最初に考えたよりも注意が必要です。

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 JOIN3つの所有者のいずれかがで見つからない場合に行の更新全体が失敗するのを防ぐために、を使用しowners_distinctます。

データベース設計

のすべての冗長データが必要table_aですか?正規化されたスキーマの標準的な方法は、 foreign keysowner1、、 )のみを格納しowner2owner3オンデマンドで名前の詳細を取得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回だけ必要とするということです。

于 2013-03-26T02:12:17.483 に答える
-1

SELECT owner、owner_surname and owner_othername FROM table_a

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
于 2013-03-26T02:29:06.340 に答える