首页 > 试题广场 >

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

[编程题]删除emp_no重复的记录,只保留最小的id对应的记录。
  • 热度指数:161817 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
删除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');

删除后titles_test表为(注:最后会select * from titles_test表来对比结果)
id
emp_no
title
from_date
to_date
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


示例1

输入

drop table if exists titles_test;
CREATE TABLE 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');

输出

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
先按照emp_no对表进行分组,然后找到每个组最小的id号,然后进行判断删除
SELECT * FROM titles_test WHERE id NOT IN(SELECT MIN(id) FROM titles_test GROUP BY emp_no);

发表于 2017-09-01 01:57:52 回复(1)