본문 바로가기
프로그램

[MySQL] You can't specify target table '테이블명' for update in FROM clause

by 공공정보 2021. 3. 17.
728x90

 

서브 쿼리를 이용한 데이터 입력, 수정, 삭제를 쉽게 처리 해보자...

 

MS-SQL 쿼리문으로는 전혀 문제없이 잘 돌아가는 쿼리를 MySQL에 실행하면 이상하게 에러가 발생한다...

 

You can't specify target table 'temp1' for update in FROM clause

 

테이블 지정이 불가능하다고 하니... 어떤 문법을 사용해야 할지..

 

검색을 해보니 단순하네... from 절 괄호로 묶어서 다른이름으로 지정해 주면 해결이 된다...

 

그럼 테스트를 해보자..

 

테이블 생성부터... 근데 임시 테이블로 생성을 했더니 같은 테이블 2번 연다고 에러가 발생하여 어쩔수 없이 실제 테이블을 생성했다.


create table temp1(idx int AUTO_INCREMENT, id int, name varchar(30), age int, PRIMARY KEY (`idx`));
create table temp2(idx int AUTO_INCREMENT, id int, name varchar(30), age int, PRIMARY KEY (`idx`));

 

테이블 생성이 완료 되었으면, 임시 테이터를 입력해 보자..

 

insert into temp1(id, name, age)
select 1, '아빠', 50
union all
select 2, '개똥이', 18
union all
select 3, '영이', 18
union all
select 4, '오빠', 25
union all
select 5, '할머니', 60
union all
select 6, '철이', 18
union all
select 7, '엄마', 45
union all
select 8, '말똥이', 18;

데이터 복사도 해보고...

 

데이터 복사 때도 Union all 사용해보니 같은 테이블 2번 연다고 에러나서... 어쩔수 없이 2번 실행함.

 

insert into temp2(id, name, age)
select id, name, age from temp1;
insert into temp2(id, name, age)
select id, name, age from temp1;

-- 그냥 업데이트 테스트
update temp2 set age=19 where age=18;

 

이제 수정및 삭제 문을 실행해 보자..

하나는 에러(MS-SQL 에서는 정상 작동함^^)가 나고 하나는 정상적으로 작동한다.

 

-- 에러발생함 You can't specify target table 'temp1' for update in FROM clause
update temp1 set age=(select age from temp1 where id=temp1.id limit 1);
-- 정상 작동
update temp1 set age=(select age from (select id, age from temp1) main where id=temp1.id limit 1);

-- 에러발생함 You can't specify target table 'temp2' for update in FROM clause
delete from temp2 
where idx not in (select max(idx) idx from temp2 group by id);
-- 정상 작동
delete from temp2 
where idx not in (select idx from (select max(idx) idx from temp2 group by id) main);

-- 내용 확인용
select * from temp1;
select * from temp2;

 

temp1 테이블 내용

 

 

 

temp2 테이블 내용

 

 

 

 

전체 소스 다운로드

 

blog.naver.com/spprince/222277994155

 

#MySQL #일괄업데이트 #서브쿼리 #SQL

 


 

본 블로그의 글은 공공정보와 개인적 생각의 글 임을 알려드립니다.

또한 오류가 있는 부분이 있으면 댓글로 알려주시기 바랍니다.

 

감사합니다.

반응형

댓글