使用子查询从表中删除

时间:2012-07-15 09:50:59

标签: mysql subquery sql-delete

我有这个表“autos”

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

我希望从此表中删除除行之外的所有行,其中每个auto的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
)

请告诉我,如何制作这个?

2 个答案:

答案 0 :(得分: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
)

答案 1 :(得分: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)

希望这有帮助!