从表中删除重复的行

时间:2011-09-28 11:27:12

标签: mysql sql

id     lat                long     speed      date          address
 1    22.92138131   72.44103313     3.96 km/h     2011-09-26  National, Gujarat, India
 2    22.92138145   72.44103413     13.96 km/h     2011-09-26  National, Gujarat, India
 3    22.92138134   72.44103423     15.96 km/h     2011-09-26  National, Gujarat, India
 4    22.92138454   72.44103233     13.96 km/h     2011-09-26  10t ring Rd, Nehru Nagar
 5    22.92138354   72.44102533     13.96 km/h     2011-09-26  Anandnagar Rd, Ahmedabad
 6    22.92138484   72.44103293     19.96 km/h     2011-09-26  Anandnagar Rd, Ahmedabad

我想写一个查询,结果如下:

id     lat                long     speed      date          address
 1    22.92138131   72.44103313     3.96 km/h     2011-09-26  National, Gujarat, India
 4    22.92138454   72.44103233     13.96 km/h     2011-09-26  10t ring Rd, Nehru Nagar
 5    22.92138354   72.44102533     13.96 km/h     2011-09-26  Anandnagar Rd, Ahmedabad

我想根据地址删除重复的行。

6 个答案:

答案 0 :(得分:9)

要检查您要删除的内容:

SELECT distinct t1.*
  FROM yourtable as t1
  join yourtable as t2
 WHERE t1.address = t2.address
   and t1.id < t2.id

如果您对此感到满意:

DELETE t1
  FROM yourtable as t1
  join yourtable as t2
 WHERE t1.address = t2.address
   and t1.id < t2.id

这样,您可以使用id列

上的最大值保留记录

答案 1 :(得分:4)

如果你不关心你保留哪一行

ALTER IGNORE TABLE table ADD UNIQUE KEY 'address' (`address`);

'IGNORE'很重要,这意味着默默地忽略重复数据。 (即在插入表格的“新版本”时忽略它。)

可能要删除指数afterwoods

ALTER TABLE table DROP KEY 'address';

答案 2 :(得分:2)

假设您希望返回ID值最小的行:

SELECT 
    *
FROM
TABLENAME T INNER JOIN
(
    SELECT MIN(ID) AS ID FROM TableName 
    GROUP BY Address
) SUB ON T.ID = SUB.ID

答案 3 :(得分:2)

需要使用当前表格所具有的相同字段创建重复/临时表。

然后执行以下SQL

首先清除临时表:

DELETE FROM `#TMP_TABLE#`;

根据您的期望在临时表中插入记录。

INSERT INTO `#TMP_TABLE#`
SELECT T . *
FROM #TABLE# T
INNER JOIN (
    SELECT MIN( ID ) AS ID
    FROM #TABLE#
    GROUP BY address
    ) SUB ON T.id = SUB.id

截断主表

DELETE FROM `#TABLE#`;

从临时表中复制数据

INSERT INTO #TABLE# SELECT * FROM  `#TMP_TABLE#`

答案 4 :(得分:0)

delete from table_name tb where id not in 
   (select min(id) from table_name tb1 group by address)

我认为您要删除具有地址重复性的行并希望在表中保留最小ID行

答案 5 :(得分:0)

您可以通过执行以下3个简单步骤轻松完成此操作,因此可以使用3个SQL语句:

步骤1:将非重复项(唯一元组)移动到临时表中 CREATE TABLE new_table as SELECT * FROM old_table WHERE 1 GROUP BY [用于删除重复项的列;]

第2步:删除删除旧表 我们不再需要包含所有重复条目的表,所以放弃它! DROP TABLE old_table;

步骤3:将new_table重命名为old_table的名称 RENAME TABLE new_table TO old_table;

另一种方式你可以去Bellow Link ...它也是一个好方法......很难但是声明较少 http://dev.mysql.com/doc/refman/5.0/en/insert.html