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
全部评论

相关推荐

牛舌:如果我不想去,不管对方给了多少,我一般都会说你们给得太低了。这样他们就会给下一个offer的人更高的薪资了。
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务