2013-02-09 5 views
2

INSERT ... ON DUPLICATE KEY UPDATE을 사용하여 조금 복잡한 업 샘플 작업을 수행하고 싶습니다. 그러나 나는 그것을 작동시키지 못했습니다.여분 체크가있는 MySQL 업다운

  1. 레코드를 삽입하십시오 :

    이 내가하고 싶은 것입니다. 삽입이 성공하면 좋습니다.

  2. 해당 레코드가 있으면 해당 레코드를 업데이트하십시오.
  3. 레코드를 업데이트 할 때 check_status 필드가 1이면 설명 및 설명 필드를 그대로 둡니다.
  4. 레코드를 업데이트 할 때 check_status 필드는 0이고 설명 및 주석 필드도 업데이트됩니다.

은 SQL을 작성하기 전에,이 some_table에 다음과 같은 기록이 있다고 가정하자 :

을 다음과 같이 그래서 제가 위에서 설명 된 작업을 수행하기 위해, 내가 SQL을 사용
column name  | val 
-----------------+------------------------- 
some_unique_key | 32 
description  | existing description 
comment   | existing comment 
check_status  | 1 

INSERT INTO some_table ('description', 'comment', 'some_unique_key') 
VALUES ('some description', 'some comment', 32) 
ON DUPLICATE KEY UPDATE 
description = IF(check_status = 1, VALUES(description), 'some description') 
comment = IF(check_status = 1, VALUES(comment), 'some comment') 

VALUES (description)가 DB 테이블의 기존 레코드 (예 : '기존 설명')의 값을 줄 것이라고 생각했습니다. 그러나, 그것은 내가 삽입하려고했던 것, 즉 '약간의 묘사'를주는 것처럼 보인다.

누구나 SQL을 사용하여 올바르게 수행하는 방법을 알고 있습니까? 업서 트하려고 할 때 기존 레코드의 값을 참조하는 가장 좋은 방법은 무엇입니까?

답변

5

심플. (당신은 이미 check_status의 기존 값을 참조 할을하고있는) VALUES()를 사용하지 마십시오

INSERT INTO some_table ('description', 'comment', 'some_unique_key') 
VALUES ('some description', 'some comment', 32) 
ON DUPLICATE KEY UPDATE 
description = IF(check_status = 1, description, 'some description') 
comment = IF(check_status = 1, comment, 'some comment') 

을 또는 오히려 자신을 반복하는 것보다 새로운 콘텐츠를 설정하는 데 사용

INSERT INTO some_table ('description', 'comment', 'some_unique_key') 
VALUES ('some description', 'some comment', 32) 
ON DUPLICATE KEY UPDATE 
description = IF(check_status = 1, description, VALUES(description)) 
comment = IF(check_status = 1, comment, VALUES(comment)) 
+0

하하. 아, 그게 간단했습니다! @eggyal! 답변 주셔서 감사합니다! –

관련 문제