2011-01-10 9 views
5

コードを削除しますは、複数のテーブルに参加

create table coltype (coltype varchar(5)); 

insert into coltype values ('typ1'); 

create table colsubtype (coltype varchar(5), colsubtype varchar(5)); 

insert into colsubtype values ('typ2', 'st1'); 
insert into colsubtype values ('typ2', 'st2'); 

create table table1 (col1 varchar(5), coltype varchar(5), colsubtype varchar(5)); 

insert into table1 values ('val1','typ1', 'st1'); 
insert into table1 values ('val2','typ1', 'st2'); 
insert into table1 values ('val3','typ1', 'st3'); 
insert into table1 values ('val4','typ2', 'st1'); 
insert into table1 values ('val5','typ2', 'st2'); 
insert into table1 values ('val6','typ2', 'st3'); 
insert into table1 values ('val7','typ3', 'st1'); 
insert into table1 values ('val8','typ3', 'st2'); 
insert into table1 values ('val9','typ3', 'st3'); 

commit; 

基本的に、私はcoltypecolsubtypecoltypecolsubtype表に記載されていないすべてのレコードを削除したいです。

どうすればいいですか?以下は私が取ることを考えていた道ですが、うまくいかない - それは良いデザインのようには見えません。

delete from table1 
where coltype != (select coltype from coltype) 
    OR not (coltype = cst.coltype and colsubtype = cst.colsubtype 
from (select coltype, colsubtype from colsubtype) cst) 
+0

悪いサンプルデータ? 'colsype'テーブルへの挿入で' typ2 'を 'coltype'として参照しますが、その値を' coltype'テーブルに挿入しませんでした。 –

答えて

2

これを試してください

delete from table1 
where not exists 
     (
     select * 
     from coltype 
     where table1.coltype = coltype.coltype 
     ) 
    and not exists 
     (
     select * 
     from colsubtype 
     where table1.coltype = colsubtype.coltype 
      and table1.colsubtype = colsubtype.colsubtype 
     ) 
0

あなたのコードは、EXISTS、NOT使用 "が存在しない" オペレータかなり重く

delete from table1 
where not exists 
(
    select 1 from colType ct where ct.colType = table1.colType 
) 
and not exists 
(
    select 1 from colsubtype cst where cst .colSubType = table1.colSubType 
) 
+0

上記は正常に機能しましたが、「typ3」レコードもすべて削除されている必要があります。 –

0
DELETE FROM table1 
WHERE coltype IN 
(SELECT coltype 
FROM table1 
WHERE coltype NOT IN (SELECT coltype FROM coltype)) 
OR colsubtype IN 
(SELECT colsubtype 
FROM table1 
WHERE colsubtype NOT IN (SELECT colsubtype FROM colsubtype)) 
+0

申し訳ありませんが、ANDでなくANDである必要があります。私は今編集しました – Dunc

8

を活用する必要があります。LEFTを使用して

delete from t1 
    from table1 t1 
    where not exists (select null from coltype ct where ct.coltype = t1.coltype) 
     or not exists (select null from colsubtype cst where cst.colsubtype = t1.colsubtype) 

ジョイン:

delete from t1 
    from table1 t1 
     left join coltype ct 
      on t1.coltype = ct.coltype 
     left join colsubtype cst 
      on t1.colsubtype = cst.colsubtype 
    where ct.coltype is null 
     or cst.colsubtype is null 
+0

最初に見つかった/最初の 'from'はオプションであることを思い出しました。 Phew –

関連する問題