删除具有相同列值的记录?

时间:2018-10-01 15:29:58

标签: mysql

好吧,我有一些表,其中的某些记录具有相同的address_id,我想将它们全部删除,或者(如果可能)在第一个记录之后删除所有记录,例如:

AbsoluteMaxBytes

在这种情况下,我想删除ID为(2,5,6)的记录。

这是我的查询,但出现错误:

  

您无法在FROM中指定目标表“ person_address”进行更新   条款

id | person_id | address_id
1       80            3
2       226           3
3       31            5
4       46            9
5       11            9
6       123           9

选择效果很好。

3 个答案:

答案 0 :(得分:1)

您的选择似乎也不正确。您可以尝试这样-

delete from person_address
 where id not in (select *
                    from (SELECT min(id)
                            FROM person_address
                           WHERE person_address.person_id < 400000
                           GROUP BY address_id) temp)
   and person_id < 400000

答案 1 :(得分:0)

可以通过使同一表的2个对象删除重复记录。 喜欢

Delete p1 
from person_address p1, person_address p2
where
p1.person_id < 400000
and p1.address_id = p2.address_id
and p1.id > p2.id;

答案 2 :(得分:0)

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,person_id INT NOT NULL
,address_id INT NOT NULL
);

INSERT INTO my_table VALUES
(1    ,   80       ,     3),
(2     ,  226  ,         3),
(3     ,  31   ,         5),
(4     ,  46   ,         9),
(5     ,  11   ,         9),
(6     ,  123  ,         9);

CREATE TABLE my_new_table AS
SELECT x.* FROM my_table x JOIN (SELECT MIN(id) id FROM my_table GROUP BY address_id) y ON y.id = x.id;

SELECT * FROM my_new_table;
+----+-----------+------------+
| id | person_id | address_id |
+----+-----------+------------+
|  1 |        80 |          3 |
|  3 |        31 |          5 |
|  4 |        46 |          9 |
+----+-----------+------------+
3 rows in set (0.01 sec)

ALTER TABLE my_new_table MODIFY id SERIAL PRIMARY KEY;

ALTER TABLE my_new_table MODIFY address_id INT UNIQUE;