如何使用SQL从多个表中删除行?

时间:2013-12-30 08:51:37

标签: sql sql-server

我有3张桌子:

mainTable:
id | uniqField
--------------
1  | 1111
2  | 1111
3  | 2222
4  | 2222
5  | 3333
6  | 4444

table1:
id|name|deleted
----------
 1|Mike|0
 2|Mike|0
 5|John|0

table2:
id|name|deleted
----------
 3|Peke|0
 4|Peke|0
 6|Vels|0

那些表由id字段绑定 现在我想从这些表中删除重复项。对于mainTable我可以使用:

DELETE mainTable
FROM mainTable
LEFT OUTER JOIN (
   SELECT MIN(id) as RowId, uniqField
   FROM mainTable 
   GROUP BY uniqField
) as KeepRows ON
   mainTable.id= KeepRows.RowId
WHERE
   KeepRows.RowId IS NULL

但是在tables1和table2中,我想将deleted字段设置为0->1以重复我的意思:

1  | 1111 
2  | 1111  -> duplicate->remove

 1|Mike|0
 2|Mike|0->duplicate-> 0->1

1 个答案:

答案 0 :(得分:1)

试试这个 -

SET NOCOUNT ON;

DECLARE @mainTable TABLE
(
    id INT,
    uniqField INT
)

INSERT INTO @mainTable (id, uniqField) 
VALUES (1, 1111), (2, 1111), (3, 2222), (4, 2222), (5, 3333), (6, 4444)

DECLARE @deleted TABLE (id INT)

;WITH cte AS 
(
    SELECT *, RowNum = ROW_NUMBER() OVER (PARTITION BY uniqField ORDER BY 1/0)
    FROM @mainTable
)
DELETE FROM cte
OUTPUT DELETED.id INTO @deleted
WHERE RowNum > 1

DECLARE @table1 TABLE
(
    id INT,
    uniqField VARCHAR(10),
    deleted BIT
)

DECLARE @table2 TABLE
(
    id INT,
    uniqField VARCHAR(10),
    deleted BIT
)

INSERT INTO @table1 (id, uniqField, deleted) 
VALUES (1, 'Mike', 0), (2, 'Mike', 0), (5, 'John', 0)

INSERT INTO @table2 (id, uniqField, deleted) 
VALUES (3, 'Peke', 0), (4, 'Peke', 0), (6, 'Vels', 0)

UPDATE @table1
SET deleted = 1
FROM @deleted
WHERE [@deleted].id = [@table1].id

UPDATE @table2
SET deleted = 1
FROM @deleted
WHERE [@deleted].id = [@table2].id

SELECT * FROM @table1
SELECT * FROM @table2

输出 -

id          uniqField  deleted
----------- ---------- -------
1           Mike       0
2           Mike       1
5           John       0

id          uniqField  deleted
----------- ---------- -------
3           Peke       0
4           Peke       1
6           Vels       0