从sql中删除重复数据

elcex8rz  于 2021-06-21  发布在  Mysql
关注(0)|答案(5)|浏览(366)

我有一个名为“data”的sql数据库和一个表“disk”,其中有5列

CREATE TABLE `disk` (
  `id` int(11) NOT NULL,
  `title` text COLLATE utf8_unicode_ci NOT NULL,
  `link` text COLLATE utf8_unicode_ci NOT NULL,
  `mag` text COLLATE utf8_unicode_ci NOT NULL,
  `size` varchar(10) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

“mag”列包含一些重复项。
我想删除mag列相同的完整行。
注:假设mag列有1,2,3,4,4,5。。。。我想从中删除一个重复的4。意思是我不想把这4个都删掉。必须保留一个“4”。
对它的查询应该是什么样的?

daolsyd0

daolsyd01#

您可以执行以下操作。。
创建新表并保留随机行:
第一个复制表 disk (唯一数据)到临时表 disk2 .
删除表格 disk .
重命名临时表 disk2disk .

create table disk2 select * from disk group by d;

drop table disk;

rename table disk2 to disk;

注意:这里我们使用 group by* 因为op不在乎保留哪一行。
创建新表并保留具有最小或最大id的行:另一种在保留具有最小或最大id的行时执行此操作的方法 min 或者 max 身份证件

/*copy data from disk to temp table disk2*/
create table disk2 select * from disk
    where id in (select min(id) from disk group by d);
/*drop table disk*/
drop table disk;
/*rename temp table to disk*/
rename table disk2 to disk;

更新:另一种方法
从现有表中删除重复项

/*first create a dups table for duplicates*/
    create table dups select * from disk
        where id not in (select min(id) from disk group by d);
    /*now delete all rows which are present in dups table*/
    delete from disk where id in (select id from dups);
    /*now delete the dups table*/
    drop table dups;
58wvjzkj

58wvjzkj2#

delete from disk
where id  in 
(
select id 
from task
group by id 
having count(id) >1
)
6g8kf2rb

6g8kf2rb3#

试试这个:

DELETE disk
FROM disk
INNER JOIN (
       SELECT id,
               d,
               CASE WHEN d = @prevd 
                       THEN @id:=@id+1
                    ELSE @id:=1
               END AS rankNum,
               @prevd:=d AS prd
       FROM disk, (SELECT @prevd:=NULL,@id:=NULL) t
      ) t1
ON disk.id = t1.id
WHERE rankNum >= 2;

如需演示,请点击以下链接:
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=318e94a135853fcd15b14e4b8bbf1fdc

0kjbasz6

0kjbasz64#

尝试以下操作以删除具有相同d列的重复项,并保留一行具有最低id值:

DELETE d1 
FROM  disk d1, disk d2 
WHERE d1.id > d2.id AND 
      d1.d = d2.d;
t3irkdon

t3irkdon5#

不需要创建任何临时表
我希望这对你有用

DELETE ColumnName
FROM TableName
INNER JOIN 
(
    SELECT  MAX(ID) AS ID
    FROM TableName
    GROUP BY ID
    HAVING COUNT(*) > 1
) Duplicate on Duplicate.ID = TableName.ID
WHERE TableName.ID < Duplicate.lastId;

请查看以下链接以获取更多建议
mysql删除重复记录但保留最新记录

相关问题