分类: Mysql/postgreSQL
2015-09-25 18:11:28
例如,id 为主键,a 列有重复数据,想要删除 重复的a,即a相同的只保留一行,可以试试如下查询:
select * from test where id not in (select max(id) from test group by a);
把 select * 换成 delete 就是删除了
mysql> select * from test;
+------+------+------+------+
| id | a | b | c |
+------+------+------+------+
| 1 | 1 | 1 | 1 |
| 2 | 1 | 2 | 2 |
| 3 | 2 | 2 | 2 |
| 4 | 3 | 3 | 3 |
| 5 | 3 | 5 | 5 |
| 6 | 3 | 6 | 6 |
+------+------+------+------+
6 rows in set (0.12 sec)
mysql> select * from test where id not in (select max(id) from test group by a);
+------+------+------+------+
| id | a | b | c |
+------+------+------+------+
| 1 | 1 | 1 | 1 |
| 4 | 3 | 3 | 3 |
| 5 | 3 | 5 | 5 |
+------+------+------+------+
3 rows in set (0.12 sec)
mysql>