Teamテーブル Tid Ttype Tname --- ----- ----- 101 1 name1 102 2 name2 103 1 name3 104 3 name4 105 1 name5 Relationテーブル Tid Cid --- ----- 101 10003 102 10004 103 10002 104 10001 105 10005 Characterテーブル Cid Ccategory Cname ----- --------- ------- 10001 pa hawk 10002 pa buffalo 10003 pa lion 10004 pa eagle 10002 ce swallow 10003 ce giant 10005 ce tiger TeamテーブルのTtype=1のTname列を、 Tid列で紐づいたRelationテーブルのCid列で 更に紐づいたCharacterテーブルのCcategory列='ce'のレコードのCnameで更新する。 更新結果 Teamテーブル Tid Ttype Tname --- ----- ------- 101 1 giant 102 2 name2 103 1 swallow 104 3 name4 105 1 tigerこちらを参考にさせていただきました
create table Team(Tid,Ttype,Tname) as select 101,1,'name1' union all select 102,2,'name2' union all select 103,1,'name3' union all select 104,3,'name4' union all select 105,1,'name5'; create table Character(Cid,Ccategory,Cname) as select 10001,'pa','hawk' union all select 10002,'pa','buffalo' union all select 10003,'pa','lion' union all select 10004,'pa','eagle' union all select 10002,'ce','swallow' union all select 10003,'ce','giant' union all select 10005,'ce','tiger'; create table Relation(Tid,Cid) as select 101,10003 union all select 102,10004 union all select 103,10002 union all select 104,10001 union all select 105,10005;
--■■■結合update文を使わない方法■■■ update Team a set Tname = (select c.Cname from Relation b,Character c where b.Tid = a.Tid and b.Cid = c.Cid and c.Ccategory = 'ce') where Ttype='1' and exists(select 1 from Relation b,Character c where b.Tid = a.Tid and b.Cid = c.Cid and c.Ccategory = 'ce'); --■■■結合update文を使う方法■■■ update Team a set Tname = b.Cname from Character b,Relation c where a.Ttype=1 and a.Tid = c.Tid and c.cid = b.cid and b.Ccategory='ce';
結合update文は、条件の2度書きが防げて便利ですねぇ UPDATE