【问题标题】:Delete with join to multiple tables删除并加入多个表
【发布时间】:2011-01-10 17:25:24
【问题描述】:

代码:

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)

【问题讨论】:

  • 样本数据错误?您在 colsubtype 表的插入中将 'typ2' 引用为 coltype,但您没有将该值插入到 coltype 表中。

标签: sql-server join sql-delete


【解决方案1】:

使用不存在:

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

【讨论】:

  • 刚发现/被提醒第一个from是可选的。唷
【解决方案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
        ) 

【讨论】:

    【解决方案3】:

    您的代码将需要大量利用“不存在”运算符

    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
    )
    

    【讨论】:

    • 上述工作正常,除了它也应该删除所有“typ3”记录 - 它没有。
    【解决方案4】:
    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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-13
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-03
      相关资源
      最近更新 更多