sql-server - 通过连接删除多个表

标签 sql-server join sql-delete

代码:

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;

基本上,我想删除 coltype 所在的所有记录和colsubtype coltype中没有提到和colsubtype表。

我该怎么做。下面是我正在考虑采取的路径,但它不起作用 - 而且 - 它看起来不是一个好的设计。

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)

最佳答案

使用 NOT EXISTS:

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

关于sql-server - 通过连接删除多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4649547/

相关文章:

sql-server - 将分组的多个串联列返回到逗号分隔的字符串列

sql - 进行批量更新的最快方法

mysql - 列出表 1 中的所有项目并填写表 2 中匹配的信息

mysql - 我应该在删除多行后重置表索引/优化吗?

mysql - 根据条件删除 SQL 数据库中的重复项

python - 使用 pyodbc 时为 "CREATE ... statement not allowed within multi-statement transaction"

sql-server - 在获取错误信息的同时获取列名

r - 识别数据框 A 中未包含在数据框 B 中的记录

sql - 这种类型的连接在最后被限定时被称为什么?

mysql 哪里计数(column_name)= 1?