删除两个值匹配的行mysql

时间:2015-03-03 22:07:05

标签: mysql

我想要除了一行包含相同数据的所有行,问题是数据在多个字段中。

|id | ValA | ValB  |
|1  | abc  | abc   |
|2  | abc  | abc   |
|3  | abc  | def   |

在上面的示例表中,我想删除ID为2的行,并保留1和3.

我能找到的唯一解决方案是在PHP中使用循环,但我有170万条记录,所以我不知道循环所有这些值。

我认为" SQL-way"将是次级查询,但我无法解决它们

由于

2 个答案:

答案 0 :(得分:1)

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,vala CHAR(3) NOT NULL
,valb CHAR(3) NOT NULL
);

INSERT INTO my_table VALUES
(1  ,'abc','abc'),
(2  ,'abc','abc'),
(3  ,'abc','def');

SELECT * FROM my_table;
+----+------+------+
| id | vala | valb |
+----+------+------+
|  1 | abc  | abc  |
|  2 | abc  | abc  |
|  3 | abc  | def  |
+----+------+------+


SELECT * 
  FROM my_table x 
  LEFT 
  JOIN my_table y 
    ON y.vala = x.vala 
   AND y.valb = x.valb 
   AND y.id < x.id;
+----+------+------+------+------+------+
| id | vala | valb | id   | vala | valb |
+----+------+------+------+------+------+
|  1 | abc  | abc  | NULL | NULL | NULL |
|  2 | abc  | abc  |    1 | abc  | abc  |
|  3 | abc  | def  | NULL | NULL | NULL |
+----+------+------+------+------+------+

SELECT x.* 
  FROM my_table x 
  LEFT 
  JOIN my_table y 
    ON y.vala = x.vala 
   AND y.valb = x.valb 
   AND y.id < x.id 
 WHERE y.id IS NULL;
+----+------+------+
| id | vala | valb |
+----+------+------+
|  1 | abc  | abc  |
|  3 | abc  | def  |
+----+------+------+

SELECT x.*  
  FROM my_table x 
  JOIN my_table y 
    ON y.vala = x.vala 
   AND y.valb = x.valb 
   AND y.id < x.id;
+----+------+------+
| id | vala | valb | 
+----+------+------+
|  2 | abc  | abc  | 
+----+------+------+

DELETE x 
  FROM my_table x 
  JOIN my_table y 
    ON y.vala = x.vala 
   AND y.valb = x.valb 
   AND y.id < x.id;

SELECT * FROM my_table;
+----+------+------+
| id | vala | valb |
+----+------+------+
|  1 | abc  | abc  |
|  3 | abc  | def  |
+----+------+------+

答案 1 :(得分:0)

也许是这样的:

DELETE t1 FROM 'mytable' t1
  JOIN 'mytable' t2 ON (t1.ValA = t2.ValA) AND (t1.ValB = t2.ValB)
WHERE t1.id > t2.id