以下 CROSS JOIN 如何删除比较相同记录的记录
Following CROSS JOIN how to remove records comparing same record
我进行了 CROSS JOIN,将每条记录与所有其他记录进行比较。
但是,我想删除那些正在比较相同记录的记录。
最有效的方法是什么?
不完全确定您是否希望在有重复项时从两个表中删除记录,但我会这样做。
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;
这是您要找的吗?
SELECT *
FROM Table1
CROSS JOIN Table2
WHERE Table1.PrimaryKey <> Table2.PrimaryKey
我进行了 CROSS JOIN,将每条记录与所有其他记录进行比较。
但是,我想删除那些正在比较相同记录的记录。
最有效的方法是什么?
不完全确定您是否希望在有重复项时从两个表中删除记录,但我会这样做。
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;
这是您要找的吗?
SELECT *
FROM Table1
CROSS JOIN Table2
WHERE Table1.PrimaryKey <> Table2.PrimaryKey