61 Star 427 Fork 145

xuthus / 数据库SQL实战

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
42.删除emp_no重复的记录只保留最小的id对应的记录.md 1.07 KB
一键复制 编辑 原始数据 按行查看 历史
xuthus 提交于 2019-08-12 23:23 . add:all

删除emp_no重复的记录,只保留最小的id对应的记录。

题目描述

删除emp_no重复的记录,只保留最小的id对应的记录。

CREATE TABLE IF NOT EXISTS titles_test (
id int(11) not null primary key,
emp_no int(11) NOT NULL,
title varchar(50) NOT NULL,
from_date date NOT NULL,
to_date date DEFAULT NULL);

insert into titles_test values ('1', '10001', 'Senior Engineer', '1986-06-26', '9999-01-01'),
('2', '10002', 'Staff', '1996-08-03', '9999-01-01'),
('3', '10003', 'Senior Engineer', '1995-12-03', '9999-01-01'),
('4', '10004', 'Senior Engineer', '1995-12-03', '9999-01-01'),
('5', '10001', 'Senior Engineer', '1986-06-26', '9999-01-01'),
('6', '10002', 'Staff', '1996-08-03', '9999-01-01'),
('7', '10003', 'Senior Engineer', '1995-12-03', '9999-01-01');

答案

delete from titles_test where id not in (select min(t.id) from titles_test t group by t.emp_no)

题解

1、获取去重后的最小ID临时表

select min(t.id) from titles_test t group by t.emp_no

2、将不在临时表中的所有数据删除

SQL
1
https://gitee.com/xuthus5/Database-SQL-Actual-Combat.git
git@gitee.com:xuthus5/Database-SQL-Actual-Combat.git
xuthus5
Database-SQL-Actual-Combat
数据库SQL实战
master

搜索帮助