我正在尝试编写我的第一个mySQL查询。如果行具有相同的article-number字段,我需要删除它们。我写了这个问题:
SELECT
article_number, COUNT(*)
FROM
article_numbers
GROUP BY
article_number
HAVING
COUNT(*) > 1
它显示了所有重复的行。但是如何为每个副本删除除1之外的所有内容?
由于
编辑:
我尝试了这个查询:
delete article_numbers from article_numbers inner join
(select article_number
from article_numbers
group by article_number
having count(1) > 1) as duplicates
on (duplicates.article_number = article_numbers.article_number)
但它给了我这个错误:
无法删除或更新父行:外键约束失败(
api
。products
,CONSTRAINTproducts_article_number_id_foreign
FOREIGN KEY(article_number_id
)参考article_numbers
(id
))
编辑2:
我暂时禁用了外键,现在我的删除查询有效。但是如何修改它不会删除其中一个重复的行?
答案 0 :(得分:2)
使用CROSS JOIN
。
<强>查询强>
delete t1
from article_numbers t1,
article_numbers t2
where t1.id > t2.id
and t1.article_number = t2.article_number;
答案 1 :(得分:0)
我使用一个相当简单的查询来删除欺骗:
;WITH DEDUPE AS (
SELECT ROW_NUMBER() OVER(
PARTITION BY article_number
ORDER BY (SELECT 1)) AS RN
FROM article_numbers)
DELETE FROM DEDUPE
WHERE RN != 1
答案 2 :(得分:0)
Delete c
from (select *,rank() over(order by article_number) as r from article_numbers )c
where c.r!=1
答案 3 :(得分:0)
如果存在相同的article_number但存在更高的ID,则删除一行:
delete from article_numbers t1
where exists (select 1 from article_numbers t2
where t2.article_number = t1.article_number
and t2.id > t1.id)
核心ANSI SQL,所以我认为它适用于MySQL和SQL Server。
答案 4 :(得分:0)
我认为这会有所帮助:
WITH tblTemp as
(
SELECT ROW_NUMBER() Over(PARTITION BY Name,Department ORDER BY Name)
As RowNumber,* FROM <table_name>
)
DELETE FROM tblTemp where RowNumber >1
答案 5 :(得分:0)
我修改了我的查询,我认为它现在有效:
SET FOREIGN_KEY_CHECKS=0;
delete article_numbers from article_numbers inner join
(select min(id) minid, article_number
from article_numbers
group by article_number
having count(1) > 1) as duplicates
on (duplicates.article_number = article_numbers.article_number and duplicates.minid <> article_numbers.id)
但似乎非常复杂。我会检查@Ullas方法,看它是否也有效。