1

例如,我有这个表“汽车”

id | name
--------------
2  | Mercedes
5  | Mercedes
6  | Mercedes
7  | BMW 
9  | BMW 

我想从这个表中删除所有行,除了行,其中每个汽车的 id 是最大的。也就是说,我想删除后,在表中只剩下这几行:

6 | Mercedes
9 | BMW 

我写了这个查询,但这不起作用(也不返回错误)。

DELETE FROM autos WHERE id NOT IN (
    SELECT id FROM (
        SELECT MAX(id) FROM autos GROUP BY name
    ) AS t
)

请告诉我,这个怎么做?

4

2 回答 2

2

AFAIK,以下应该有效:

DELETE FROM autos WHERE id NOT IN (
    SELECT max_id FROM (
        SELECT MAX(id) as max_id, name FROM autos GROUP BY name
    ) as t
)
于 2012-07-15T09:58:05.900 回答
1
CREATE TABLE autos (`id` int AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(30));


INSERT INTO autos(name) VALUES ('Mercedes');
INSERT INTO autos(name) VALUES ('Mercedes');
INSERT INTO autos(name) VALUES ('Mercedes');

INSERT INTO autos(name) VALUES ('BMW');
INSERT INTO autos(name) VALUES ('BMW');
INSERT INTO autos(name) VALUES ('BMW');

DELETE FROM autos 
WHERE id NOT IN (
   SELECT id FROM ( 
       SELECT max(id) id FROM autos a GROUP BY a.name 
   ) a
);

Query OK, 4 rows affected (0.14 sec)

希望这可以帮助!

于 2012-07-15T10:04:51.097 回答