从mysql中的表中删除连续的重复项

时间:2015-03-02 08:12:43

标签: php mysql

我有一个数据库,其中表包含连续的重复行。带数据的表的演示如下。

id  name  processed
 1  xyz      0
 2  xyz      0
 3  ABC      0
 4  ABC      0

我想删除此表中的连续副本,一旦删除重复,则更新处理为1.因此最终表格如下所示。

id  name  processed
 1  xyz      1
 3  ABC      1

我这样做。

SET @v1 := (select group_concat(`id`) from `names` as m1 where 0 < (select count(*) from `names` as m2 where m2.`id` = m1.`id` - 1 and m2.`name` = m1.`name`));
DELETE FROM names WHERE id IN (@v1);
UPDATE names SET `processed`=1 WHERE `processed`=0

查询工作正常,但一次删除一行。请帮我解决这个问题。我希望删除所有选中的行。 提前谢谢。

5 个答案:

答案 0 :(得分:1)

正如@MarkBaker已在评论中写道,您可以尝试DELETE FROM table WHERE name=name and id>id

但这只能解决已经完成的事情。要阻止,您应该将unique索引添加到name列。这应该可以防止将来添加任何重复项。

虽然你有重复项,但你不能设置unique索引,所以你需要首先清理:)

答案 1 :(得分:1)

您无法在同一查询中更新和删除。所以这几乎让你失望:

DROP TABLE IF EXISTS my_table;
CREATE  TABLE my_table 
(id  INT NOT NULL AUTO_INCREMENT PRIMARY KEY,name  CHAR(3) NOT NULL,processed TINYINT NOT NULL DEFAULT 0);

INSERT INTO my_table VALUES
(1  ,'xyz',      0),
(2  ,'xyz',      0),
(3  ,'ABC',      0),
(4  ,'ABC',      0);

SELECT * FROM my_Table;
+----+------+-----------+
| id | name | processed |
+----+------+-----------+
|  1 | xyz  |         0 |
|  2 | xyz  |         0 |
|  3 | ABC  |         0 |
|  4 | ABC  |         0 |
+----+------+-----------+

SELECT y.* FROM my_table x JOIN my_table y ON y.id = x.id + 1 AND y.name = x.name;
+----+------+-----------+
| id | name | processed |
+----+------+-----------+
|  2 | xyz  |         0 |
|  4 | ABC  |         0 |
+----+------+-----------+

DELETE y FROM my_table x JOIN my_table y ON y.id = x.id + 1 AND y.name = x.name;
Query OK, 2 rows affected (0.00 sec)


UPDATE my_table SET processed = 1;
Query OK, 2 rows affected (0.00 sec)

SELECT * FROM my_table;
+----+------+-----------+
| id | name | processed |
+----+------+-----------+
|  1 | xyz  |         1 |
|  3 | ABC  |         1 |
+----+------+-----------+

答案 2 :(得分:0)

对于 PHP MySQL ,如果您的所有数据都是连续对,那么这将有效。

$con = mysqli_connect('host', 'user', 'pass', 'db');
$query ="select m1.id from names as m1 where 0 < (select count(*) from names as m2 where m2.id = m1.id - 1 and m2.name = m1.name)";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result)){
  $query2 ="DELETE FROM names WHERE id = ".$row['id'];
  mysqli_query($con, $query2);
  $id = $row['id']-1;
  $query3 ="UPDATE names SET `processed`=1 WHERE id = ".$id;
  mysqli_query($con, $query3);
}

我查了一下它的工作正常。希望它也适合你。

答案 3 :(得分:-1)

这不会编辑你的表,但会给你带有所需结果的SELECT:

SELECT min(id) id, name, 1 processed
FROM mytable
GROUP BY name

您可以在CREATE TABLE newtable AS SELECT ...,然后DROP mytable,最后到ALTER TABLE newtable RENAME TO mytable使用此功能。

答案 4 :(得分:-1)

DISTINCT关键字可用于仅返回不同(不同)的值。 使用此查询:

SELECT DISTINCT `id`, `name`,`1` AS processed
FROM mytable;