删除MySQL中的重复项

时间:2010-04-18 01:12:55

标签: mysql insert alter-table

查询是这样的:

CREATE TABLE `query` (
`id` int(11) NOT NULL auto_increment,
`searchquery` varchar(255) NOT NULL default '',
`datetime` int(11) NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM

首先我要删除表格:

ALTER TABLE `querynew` DROP `id`

然后删除双重条目.. 我尝试过:

INSERT INTO `querynew` SELECT DISTINCT * FROM `query`

但没有成功.. :(

ALTER TABLE query ADD UNIQUE ( searchquery ) - 是否可以只保存一次查询?

3 个答案:

答案 0 :(得分:2)

我会使用MySQL的多表删除语法:

DELETE q2 FROM query q1 JOIN query q2 USING (searchquery, datetime)
WHERE q1.id < q2.id;

答案 1 :(得分:0)

您应该可以在不先删除列的情况下执行此操作:

DELETE FROM `query`
 WHERE `id` IN (
        SELECT `id`
          FROM `query` q
         WHERE EXISTS ( -- Any matching rows with a lower id?
                SELECT *
                  FROM `query`
                 WHERE `searchquery` = q.`searchquery`
                   AND `datetime` = q.`datetime`
                   AND `id` < q.`id`
               )
       );

您也可以通过临时表:

SELECT MIN(`id`), `searchquery`, `datetime`
  INTO `temp_query`
 GROUP BY `searchquery`, `datetime`;

DELETE FROM `query`;

INSERT INTO `query` SELECT * FROM `temp_query`;

答案 2 :(得分:0)

我会使用带有MySQL特定IGNORE关键字的索引来执行此操作。这会一举两得:它会删除重复的行,并添加一个唯一的索引,这样你就不会再获得它们了。它通常比其他方法更快:

alter ignore table query add unique index(searchquery, datetime);