2015-03-02 84 views
1

我有一個數據庫,其中表包含連續的重複行。有數據表的演示如下。從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 

該查詢工作正常,但一次刪除一行。請幫助我。我想要刪除所有選定的行。 在此先感謝。

+0

'DELETE FROM表WHERE名稱=名稱和ID> id' – 2015-03-02 08:13:52

回答

0

對於PHPMySQL的,如果你的所有數據是連續配對,那麼這將正常工作。

$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); 
} 

我檢查了它,它的工作正常。希望它也適用於你。

1

由於@MarkBaker已發表評論,您可以嘗試DELETE FROM table WHERE name=name and id>id

但這隻適用於已經完成的工作。要阻止那,你應該加unique索引到name列。這應該可以防止未來添加任何重複項。

您不能設置,當你有重複的,所以你需要清潔第一:)

+0

這是好的,但我還需要刪除重複後更新處理的值。你不覺得這種方式的查詢比比較連續的行要花費很多時間嗎?據我所知,重複總是連續的。數據從某個地方傳出,我只有數據庫。所以你建議我不能實現。 – user2656780 2015-03-04 12:49:46

-1

這不會修改你的表,但會給你想要的結果選擇unique指數:

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

-1

DISTINCT關鍵字可用於僅返回不同的(不同的)值。 使用此查詢:

SELECT DISTINCT `id`, `name`,`1` AS processed 
FROM mytable; 
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 | 
+----+------+-----------+