ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 1:n 관계에서 update : insert & update, auto_increment 초기화
    카테고리 없음 2021. 7. 27. 16:28

    1:n 관계에서 n 관계인 경우는 update 가 insert & delete & update 가 모두 포함되어 있다.

    1. insert 와 update :

    sql 문의 on duplicate key update 로 해당 PK 가 존재시 update , 없을 시 insert 로 들어간다.

    뒤에 구문은 update 가 될 컬럼만 '컬럼명=values(컬럼명)' 으로 작성해준다.

    insert into lifestyle_facility(lifeFacility_no, lifeFacility_image_name, lifeFacility_image_size, lifeFacility_title, lifeFacility_info,lifestyle_no) 
                                   values(1,'',123,'',1) 
                                   on duplicate key update 
                                   lifeFacility_image_name=values(lifeFacility_image_name), 
                                   lifeFacility_image_size=values(lifeFacility_image_size), 
                                   lifeFacility_title=values(lifeFacility_title),
                                   lifeFacility_info=values(lifeFacility_info);

    2. delete :

    같은 delete 문이지만 삭제한다면 해당 PK 가 control 단에 들어오지 않게 되므로 not in 을 사용하여

    존재하는 PK 외의 없어진 PK 만 delete 되게 설정했다. ( 해당 경우에는 insert & update 구문보다 먼저 해야 한다. )

    delete from lifestyle_facility where lifestyle_no=1 and lifeFacility_no not in(1,2,3);

    후에 PK 의 auto_increment 설정이 사라진 PK 자리를 공백으로 두기 때문에 아래의 sql문을

    저장프로시저를 이용하여 해당 sql 문도 delete 시 실행되게 해야할 거같다.

    // auto_increment 컬럼값 재정렬
    set @CNT = 0;
    update lifestyle_image set no = @CNT:=@CNT+1;// update [변경할테이블] set [auto_increment컬럼명]
    
    // auto_increment 컬럼값 초기화
    alter table lifestyle_image auto_increment=10;

     

    댓글

Designed by Tistory.