根据源删除行

时间:2015-03-07 02:37:22

标签: sql-server-2008 tsql

我有2组来自2个表的数据。

Table 1: id, type, source
Table 2: id, type, source

如果table1table2idtype之间存在匹配记录,则table2行优先,行{{1}需要删除。

有一种快速的方法吗?

3 个答案:

答案 0 :(得分:1)

如果要在表格中删除它们,则可以使用join

delete t1
    from table1 t1
    where exists (select 1 from table2 t2 where t1.id = t2.id and t1.type = t2.type)

如果您只想要一个优先考虑结果的查询,那么它们首先来自table2,然后:

select t2.*
from table2 t2
union all
select t1.*
from table1 t1
where not exists (select 1 from table2 t2 where t1.id = t2.id and t1.type = t2.type)

答案 1 :(得分:1)

最快的方式是基于加入删除:

DELETE T1
FROM TABLE1 T1
JOIN TABLE2 T2 ON T1.ID = T2.ID AND T1.TYPE = T2.TYPE

答案 2 :(得分:-1)

我最后使用暴力

;WITH 
    CTE_TBL2 AS (SELECT * FROM final WHERE source = 't1')
,   CTE_TBL1 AS (SELECT * FROM final WHERE source = 't2')
,   CTE_DEL AS
        (
            SELECT
                    *
            FROM    CTE_TBL1
            WHERE   EXISTS  (   SELECT  1 
                                FROM    CTE_TBL2 
                                WHERE   CTE_TBL1.id     = CTE_TBL2.id 
                                AND     CTE_TBL1.type   = CTE_TBL2.type
                            )
        )
DELETE  final
FROM    final F
INNER JOIN CTE_DEL
ON      F.id        = CTE_DEL.id
AND     F.type      = CTE_DEL.type
AND     F.source    = CTE_DEL.source