这么个表,有3个字段(id, name, age),其中id是主键,name和age允许重复:
CREATE TABLE t_user (
"id" int4 NOT NULL,
"name" varchar ,
"age" int4,
PRIMARY KEY ("id")
);
INSERT INTO "public"."t_user" ("id", "name", "age") VALUES ('1', 'jim', '20');
INSERT INTO "public"."t_user" ("id", "name", "age") VALUES ('2', 'lily', '18');
INSERT INTO "public"."t_user" ("id", "name", "age") VALUES ('3', 'lucy', '18');
INSERT INTO "public"."t_user" ("id", "name", "age") VALUES ('4', 'jim', '21');
INSERT INTO "public"."t_user" ("id", "name", "age") VALUES ('5', 'jim', '22');
INSERT INTO "public"."t_user" ("id", "name", "age") VALUES ('6', 'lily', '17');
INSERT INTO "public"."t_user" ("id", "name", "age") VALUES ('7', 'hanmeimei', '16');
INSERT INTO "public"."t_user" ("id", "name", "age") VALUES ('8', 'jim', '22');
完整测试数据如下图:
1. 获取所有数据,其中相同的name只出现一次:
select * from t_user
where id in (
select min(id) from t_user
where 1 = 1
group by name
);
2. 获取所有数据,其中相同的name只出现一次,且age是相同的name中最大的:
select * from t_user
where id in (
select min(c.id) from (
select b.* from (
select name, max(age) as max_age from t_user
where 1 = 1
group by name
) a
left join t_user b on (b.name = a.name and b.age = a.max_age)
) c
group by c.name
);
3. 同理,可以实现删除重复行(某字段值重复)
delete from t_user
where id not in (
select min(id) from t_user
where 1 = 1
group by name
);