Mysql除重解决方案(两种方式)

一、DELETE e1 FROM Emp e1, Empe2 WHERE e1.name = e2.name AND e1.id > e2.id;

1.1、初始化数据

CREATE TABLE EMPLOYEE
(
  ID INT,
  NAME Varchar(100),
  DEPARTMENT INT,
  EMAIL Varchar(100)
);

INSERT INTO EMPLOYEE VALUES (1,'Tl1',101,'Tl1@ls.com');
INSERT INTO EMPLOYEE VALUES (2,'Tl2',102,'Tl2h@ls.com');
INSERT INTO EMPLOYEE VALUES (3,'Tl3',103,'Tl3h@ls.com');
INSERT INTO EMPLOYEE VALUES (4,'Tl4',104,'Tl4h@ls.com');

-- 重复的数据

INSERT INTO EMPLOYEE VALUES (5,'Tl1',101,'Tl1@ls.com');

INSERT INTO EMPLOYEE VALUES (6,'Tl2',102,'Tl2h@ls.com');

1.2、删除重复数据

DELETE e1 FROM EMPLOYEE e1, EMPLOYEE e2 WHERE e1.name = e2.name AND e1.id > e2.id;

验证一下,即可得到

select * from EMPLOYEE;

二、Mysql 8.0 新增函数 ROW_NUMBER()实现

2.1 、初始化数据,同上 1.1

2.2 、执行SQL

WITH temp AS(SELECT 
    ID,
    NAME,
    ROW_NUMBER() OVER (PARTITION BY NAME, DEPARTMENT ORDER BY id) AS row_num
FROM EMPLOYEE) SELECT temp.id,temp.name FROM temp WHERE temp.row_num=1
全部评论

相关推荐

牛客101244697号:这个衣服和发型不去投偶像练习生?
点赞 评论 收藏
分享
11-18 09:44
Java
小白也想要offer:简历别放洋屁,搞不还还放错了,当然你投外企除外,以上纯属个人观点
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务