postgres、mysql查询重复数据并删除只保留一条

postgres、mysql查询重复数据并删除只保留一条

  • 1.文章以postgres数据库为例。例如有一张用户表,id是主键,现在有id_card重复的数据。(表中id为2和5的数据)。建表sql语句在文章最后
  • 2.查询重复数据并删除
  • 3.建表以及数据sql语句

1.文章以postgres数据库为例。例如有一张用户表,id是主键,现在有id_card重复的数据。(表中id为2和5的数据)。建表sql语句在文章最后

postgres、mysql查询重复数据并删除只保留一条_第1张图片

2.查询重复数据并删除

SELECT MIN ( ID ) AS min_id FROM “user” GROUP BY id_card 。意思是根据id_card查询出所有的用户id(一个id对应一个id_card),然后执行完整sql表示将其余的id数据都删除,因为id本来就是不重复的,就达到了每条id保留一条的效果

SELECT * FROM "user" 
WHERE
	ID NOT IN ( SELECT MIN ( ID ) AS min_id FROM "user" GROUP BY id_card )
delete FROM "user" 
WHERE
	ID NOT IN ( SELECT MIN ( ID ) AS min_id FROM "user" GROUP BY id_card )

3.建表以及数据sql语句


DROP TABLE IF EXISTS "public"."user";
CREATE TABLE "public"."user" (
  "id" int4 NOT NULL,
  "name" varchar(255) COLLATE "pg_catalog"."default",
  "age" int4,
  "addtrss" varchar(255) COLLATE "pg_catalog"."default",
  "id_card" varchar(255) COLLATE "pg_catalog"."default",
  "sex" varchar(255) COLLATE "pg_catalog"."default",
  "habbit" varchar(255) COLLATE "pg_catalog"."default"
)
;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO "public"."user" VALUES (1, '王二', 16, '湖北', '420701199010125338', '男', '吃东西');
INSERT INTO "public"."user" VALUES (2, '张三', 18, '湖北', '420701198510245117', '男', '吃东西');
INSERT INTO "public"."user" VALUES (3, '李四', 25, '北京', '422105200405063117', '女', '睡觉');
INSERT INTO "public"."user" VALUES (4, '赵六', 30, '上海', '420103199707068531', '女', '睡觉');
INSERT INTO "public"."user" VALUES (5, '张三', 18, '湖北', '420701198510245117', '男', '吃东西');

-- ----------------------------
-- Primary Key structure for table user
-- ----------------------------
ALTER TABLE "public"."user" ADD CONSTRAINT "user_pkey" PRIMARY KEY ("id");

你可能感兴趣的:(mysql,mysql,数据库)