码迷,mamicode.com
首页 > 数据库 > 详细

MySQL的UPDATE或DELETE中子查询不能为同一张表

时间:2021-02-17 14:01:39      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:title   错误   engine   prim   arch   nbsp   select   min   答案   

删除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 t
where t.id not in
(select min(ti.id) from titles_test ti group by ti.emp_no)

正确答案:

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

MySQL的UPDATE或DELETE中子查询不能为同一张表

标签:title   错误   engine   prim   arch   nbsp   select   min   答案   

原文地址:https://www.cnblogs.com/liuxiangyan/p/14400800.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!