以下CROSS JOIN如何删除比较相同记录的记录

时间:2015-08-05 14:09:19

标签: cross-join

我做了一个CROSS JOIN,将每条记录与所有其他记录进行比较。

但是,我想删除那些正在比较相同记录的那些。

最有效的方法是什么?

2 个答案:

答案 0 :(得分:0)

如果有重复项,不确定是否要从两个表中删除记录,但这是我将如何做到的。

CREATE TABLE #TableA
(
    PK_A INT IDENTITY(1,1) NOT NULL,
    Field1 INT,
    Field2 VARCHAR(20),
    Field3 BIT
)
INSERT INTO #TableA (Field1, Field2, Field3) VALUES (1, 'A', 0), (1, 'B', 1), (2, 'C', 1), (3, 'C', 0)

CREATE TABLE #TableB
(
    PK_B INT IDENTITY(10,10) NOT NULL,
    Field1 INT,
    Field2 VARCHAR(20),
    Field3 BIT
)
INSERT INTO #TableB (Field1, Field2, Field3) VALUES (1, 'A', 1), (1, 'B', 1), (2, 'C', 1), (3, 'C', 1)

SELECT * FROM #TableA;
SELECT * FROM #TableB;

DECLARE @pks AS TABLE 
(
    PK_A INT,
    PK_B INT
)

INSERT INTO @pks (PK_A, PK_B)
SELECT PK_A, PK_B 
FROM #TableA INNER JOIN #TableB
ON #TableA.Field1 = #TableB.Field1
    AND #TableA.Field2 = #TableB.Field2
    AND #TableA.Field3 = #TableB.Field3

DELETE FROM #TableA WHERE PK_A IN (SELECT PK_A FROM @pks)
DELETE FROM #TableB WHERE PK_B IN (SELECT PK_B FROM @pks)

SELECT * FROM #TableA;
SELECT * FROM #TableB;

DROP TABLE #TableA;
DROP TABLE #TableB;

答案 1 :(得分:0)

这是你在找什么?

SELECT * 
FROM Table1 
CROSS JOIN Table2
WHERE Table1.PrimaryKey <> Table2.PrimaryKey