我在MySQL中有一个名为ZipCode的表,其字段为:id,zipcode,city,state。它有一些重复的记录;一些邮政编码显示两次 我想删除所有两次的zipcodes;每个邮政编码只能存储一次。 我怎样才能使它正确?
答案 0 :(得分:7)
-- remove duplicates
DELETE z1
FROM ZipCode z1, ZipCode z2
WHERE z1.zipcode = z2.zipcode AND z2.id < z1.id;
-- add a primary key
ALTER TABLE ZipCode ADD PRIMARY KEY (zipcode);
-- or a unique key
ALTER TABLE ZipCode ADD UNIQUE INDEX zipcode_unique (zipcode);
答案 1 :(得分:4)
这三个查询将删除所有重复项:
CREATE TABLE new_table AS SELECT * FROM old_table WHERE 1 GROUP BY zip;
DROP TABLE old_table;
RENAME TABLE new_table TO old_table;
答案 2 :(得分:0)
试试这个工作正常
DELETE
FROM
insurance_policy_customers ipc
WHERE
ipc.id NOT IN (SELECT
min(ipc.id)
FROM
insurance_policy_customers ipc
GROUP BY
ipc.resident_insurance_policy_id )