2011-01-10 48 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; 

基本上,我想刪除其中coltypecolsubtype未在coltypecolsubtype表中提到的所有記錄。

我該怎麼做。以下是我正在考慮的路徑,但它不起作用 - 並且 - 它似乎不是一個好的設計。

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

樣品不良?您在'colsubtype`表的插入中將'typ2'引用爲`coltype`,但是您沒有將該值插入到`coltype`表中。 – 2011-01-10 17:34:05

回答

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

您的代碼將需要利用 「不存在」 運營商非常嚴重

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」記錄 - 它沒有。 – 2011-01-10 17:37:49

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

對不起,應該是一個或不是一個。我現在編輯它 – Dunc 2011-01-10 17:38:06

8

使用EXISTS NOT:

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) 

使用LEFT JOIN的:

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`是可選的。表示不快 – 2013-05-30 18:15:29