简体   繁体   English

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

[英]How can i remove rows from several tables with SQL?

I have a 3 tables: 我有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

That tables bind by id field. 该表按id字段绑定。
Now i want to remove duplicates from this tables. 现在,我想从此表中删除重复项。 For mainTable i can use: 对于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

But in tables1 and table2 i want to set deleted field to 0->1 to duplicates I mean: 但是在table1和table2中,我要将deleted字段设置为0->1以重复,这是我的意思:

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

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

Try this one - 试试这个-

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

Output - 输出-

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

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

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

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