简体   繁体   English

查找两个SQL表之间的重复项

[英]Find duplicates between two SQL tables

I have two tables (Table1 and Table2) with the same primary keys, lets say Key1 and Key2. 我有两个具有相同主键的表(Table1和Table2),可以说Key1和Key2。 What I need to do is seperate the records in Table1 into two groups, the duplicates (records found in Table2) and the non-duplicates. 我需要做的是将表1中的记录分为两组,即重复项(在Table2中找到记录)和非重复项。 I know I could use the below, but that seems bloated and repetetive. 我知道我可以使用以下内容,但这看起来很and肿且重复。 Is there a trimmer way to do this, possibly with a single call? 有没有一种微调的方法可以做到这一点,可能只需要一个电话?

SELECT Key1, Key2 FROM Table1 WHERE Key1 IN (SELECT Key1 FROM Table2) AND Key2 IN (SELECT Key2 FROM Table2);
SELECT Key1, Key2 FROM Table1 WHERE Key1 NOT IN (SELECT Key1 FROM Table2) AND Key2 NOT IN (SELECT Key2 FROM Table2);

; ;

This call is being made from a C# ASP.NET codebehind page. 此调用是从C#ASP.NET代码隐藏页进行的。

This query does a left outer join to ensure all records from table1 are returned. 该查询执行左外部联接以确保返回table1中的所有记录。 It joins on Table2, and if there are no matches, than any columns in Table2 will be NULL for that row. 它在Table2上联接,如果没有匹配项,则该行的Table2中的任何列都将为NULL。 This behavior is used in a CASE statement to set a flag telling where the Table1 row exists in Table2 or not: 在CASE语句中使用此行为来设置标志,以告知表1行在表2中是否存在:

select t1.*,
    case when t2.Key1 is null then 'false' else 'true' end as IsDuplicate
from Table1 t1
left outer join Table2 t2 on t1.Key1 = t2.Key1
    and t1.Key2 = t2.Key2

You can then filter in your application based on the IsDuplicate column. 然后,您可以根据IsDuplicate列过滤应用程序。

在SQL2008中检查新的upsert语句SQL2008中的Upsert

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

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