我有一个位置mysql db包含3列
Country State City
US California Los Angeles
AU Queensland Brisbane
AU Victoria Southbank
AU Queensland Brisbane
如何删除mysql查询中的重复行?
DELETE FROM location WHERE country IN (
SELECT * FROM table_name
GROUP BY country, state, city
HAVING COUNT(*) >
);
我尝试了这个查询,但它没有工作
答案 0 :(得分:4)
选择不同的行并将它们放在一个新表中:
CREATE TEMPORARY TABLE location_temp AS SELECT DISTINCT * FROM location
截断表:
DELETE FROM location;
从表中填充不同的值
INSERT INTO location(Country, State, City) SELECT Country, State, City FROM location_temp;
答案 1 :(得分:3)
您的查询有很多问题:
DELETE FROM location
where country in (SELECT *
FROM table_name
GROUP BY country, state, city
having COUNT(*)>);
例如:(1)您从子查询返回多个列,但只与一列进行比较。 (2)比较后你没有号码。 (3)它指的是两个不同的表格。
数据的结构方式(行上没有唯一ID),确定要删除的行很困难。我建议你改用truncate
方法。然后学会在每个表中添加一个自动递增ID:
create temporary table tmpLocation as
select country, state, city from location;
truncate table location;
insert into location(country, state, city)
select distinct country, state, city
from tmpLocation;
drop table tmpLocation;
在具有大量删除的大型表上,这也更有效。
答案 2 :(得分:1)
您忘了提及count(*)>1
DELETE FROM location
where country in (
SELECT *
FROM table_name
GROUP BY country, state, city
having COUNT(*)>1);
仅供参考。您还可以使用ALTER IGNORE TABLE
删除重复项。
这样的事情: -
ALTER IGNORE TABLE location ADD UNIQUE INDEX (COLUMN1, COLUMN2)
答案 3 :(得分:1)
您必须使用 ALTER查询
删除重复的行ALTER IGNORE TABLE location ADD UNIQUE INDEX index_name(Country, State, City);
或otherwise
您可以使用下面的查询语法
DELETE
FROM table_name
WHERE col1 IN (
SELECT MAX(col1)
FROM tab_name
GROUP BY col1, col2, col3, ....
HAVING COUNT(*) > 1)