简体   繁体   English

基于另一个表从表中删除一系列行作为 SQL 中的输入

[英]Deleting a range of rows from a table based on another table as input in SQL

I'm using SQL Server.我正在使用 SQL 服务器。 I need help to remove a range of rows from Table1 using input values and matching Ids from Table2.我需要帮助来使用输入值和 Table2 中的匹配 ID 从 Table1 中删除一系列行。

Table1表格1

RowId行 ID SetId设置名称
1 1 1 1
2 2 1 1
3 3 1 1
4 4 1 1
5 5 1 1
6 6 1 1
7 7 1 1
8 8 1 1
9 9 1 1
1 1 2 2
2 2 2 2
3 3 2 2
4 4 2 2

Table2表2

StartId起始编号 EndId结束标识 SetId设置名称
2 2 3 3 1 1
6 6 8 8 1 1
1 1 2 2 2 2

Result Table结果表

RowId行 ID SetId设置名称
1 1 1 1
4 4 1 1
5 5 1 1
9 9 1 1
3 3 2 2
4 4 2 2

So far this is the non-working code I have.到目前为止,这是我拥有的非工作代码。 I want to Delete RowId's from Table1 where they are greater than or equal to and less than or equal to the StartId and EndId of Table2 and having matching SetId's from Table1.我想从 Table1 中删除 RowId,它们大于或等于且小于或等于 Table2 的 StartId 和 EndId,并且与 Table1 中的 SetId 匹配。

Delete From Table1
Where RowId >= 
(Select StartId From Table2 Where Table1.SetId = Table2.SetId) 
and RowId <= 
(Select EndId From Table2 Where Table1.SetId = Table2.SetId) 

you can use not exists :你可以使用not exists

select * from table1 t1
where not exists (
select 1
from table2 t2
where t1.RowId between t2.StartId and t2.EndId
and t1.setid = t2.setid
)

and if you want to delete those rows:如果你想删除这些行:

delete from table1 t1
where exists (
select 1
from table2 t2
where t1.RowId between t2.StartId and t2.EndId
and t1.setid = t2.setid
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM