简体   繁体   English

删除 SQL Server 中两个表之间的交集

[英]Delete intersection between two tables in SQL Server

I wanted to delete the matching accounts (matching on ID and acct_num) from #temp_scoring, but ended up deleting all rows from the table #temp_scoring instead.我想从 #temp_scoring 中删除匹配的帐户(匹配 ID 和 acct_num),但最终删除了表 #temp_scoring 中的所有行。 Here is the code:这是代码:

delete from #temp_scoring
where exists (
 select * from #temp_edu te
 where te.ID = ID
 and te.acct_num = acct_num)

As a side note, I would have created an alias for #temp_scoring but it was giving me a syntax error when I did that.作为旁注,我会为 #temp_scoring 创建一个别名,但是当我这样做时它给了我一个语法错误。

DELETE s
FROM
    #temp_scoring s
    INNER JOIN #temp_edu te
    ON s.ID = te.ID
    AND s.acct_num = te.acct_num

You can just do a delete with join您可以使用 join 进行删除

Your problem is the column names:您的问题是列名:

delete from #temp_scoring
where exists (
 select * from #temp_edu te
 where te.ID = ID  --- Here ID means te.ID
 and te.acct_num = acct_num  -- and acct_num means te.acct_num
)

To be clear, ID = te.ID because that is the ID the nearest enclosing scope.需要明确的是, ID = te.ID因为这是最近的封闭范围的ID

You probably want this你可能想要这个

delete ts 
from #temp_scoring ts
where exists (
 select 1
 from #temp_edu te
 where te.ID = ts.ID  
 and te.acct_num = ts.acct_num
)

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

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