2012-04-10 3 views
16

이 코드는 다음과 같습니다. 테이블에 자동 증가 필드가 있습니다 (다른 테이블에서 사용됨). 이 코드를 단순화하고 최적화하고 싶습니다.MySql : 값이있는 경우 UPDATE INSERT

$query ="SELECT * FROM models WHERE col1 = 'foo'"; 
$testResult = mysql_query($query) or die('Error, query failed');  

if(mysql_fetch_array($testResult) == NULL){ 
    //insert... 
    $query ="INSERT INTO models (col1, col2, col3) 
    VALUES ('foo', 'bar', 'alph')"; 
    $result = mysql_query($query) or die('Error, query failed'); 
}else{ 
    //update... 
    $query = "UPDATE models 
     SET col1='foo', col2='bar', col3='alph' 
     WHERE col1='foo' AND col2='bar'"; 
     $result = mysql_query($query) or die('Error, query failed');   
} 

편집 : 기본 키 ID는 자동으로 증가되는 필드입니다. 나는 이것을 바꾸고 싶지 않다. 그러나 다른 필드가 중복되면이 레코드를 업데이트하려고합니다.

+4

체크 아웃 : [INSERT ... DUPLICATE KEY UPDATE 구문 ON] (http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html) – Josh

+0

무슨 짓을 당신은 자동 증가 필드를 사용합니다. – hjpotter92

+0

이 질문은 도움이 될 것입니다 ... [자동 증가 기본 키를 갖는 MySQL에 데이터를 삽입하는 방법?] (https://stackoverflow.com/questions/8753371/how-to-insert- data-to-mysql-having-auto-incremented-primary-key) – blackandorangecat

답변

29

방법에 대한 다음 장소로 대체 ​​:

REPLACE INTO models 
(col1, col2, col3) 
VALUES 
('foo', 'bar', 'alpha') 

col1이 기본 키라고 가정하고 'foo'값이있는 행이 이미 있으면 다른 두 열을 업데이트합니다. 그렇지 않으면 새로운 행이 삽입됩니다.

+0

문제가있는 'replace'는 엔트리가 있다고 가정합니다. 그러나 사용은 모두 삽입 또는 업데이트하려고합니다. – kasavbere

+1

이름이 잘못되었습니다. 엔트리가 있다고 가정하지 않습니다. MySQL 문서에서 : "REPLACE는 INSERT와 똑같이 작동합니다. 단, 테이블의 이전 행이 PRIMARY KEY 또는 UNIQUE 인덱스의 새 행과 동일한 값을 갖는 경우 새 행이 삽입되기 전에 이전 행이 삭제됩니다. " – bobwienholt

+0

나는 그것을 몰랐다. 투표가 당신에게 - 오늘 새로운 무언가를 배웁니다! – kasavbere

6

는 "DUPLICATE KEY UPDATE ON ... INSERT"를 사용하려고 할 수 있습니다 구문

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed. For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have identical effect: 

INSERT INTO table (a,b,c) VALUES (1,2,3) 
    ON DUPLICATE KEY UPDATE c=c+1; 

UPDATE table SET c=c+1 WHERE a=1; 
The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas. 

With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row and 2 if an existing row is updated. 

If column b is also unique, the INSERT is equivalent to this UPDATE statement instead: 

UPDATE table SET c=c+1 WHERE a=1 OR b=2 LIMIT 1; 
If a=1 OR b=2 matches several rows, only one row is updated. In general, you should try to avoid using an ON DUPLICATE KEY clause on tables with multiple unique indexes. 

You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... UPDATE statement. In other words, VALUES(col_name) in the UPDATE clause refers to the value of col_name that would be inserted, had no duplicate-key conflict occurred. This function is especially useful in multiple-row inserts. The VALUES() function is meaningful only in INSERT ... UPDATE statements and returns NULL otherwise. Example: 

INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6) 
    ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b); 
That statement is identical to the following two statements: 

INSERT INTO table (a,b,c) VALUES (1,2,3) 
    ON DUPLICATE KEY UPDATE c=3; 
INSERT INTO table (a,b,c) VALUES (4,5,6) 
    ON DUPLICATE KEY UPDATE c=9; 
If a table contains an AUTO_INCREMENT column and INSERT ... UPDATE inserts a row, the LAST_INSERT_ID() function returns the AUTO_INCREMENT value. If the statement updates a row instead, LAST_INSERT_ID() is not meaningful. However, you can work around this by using LAST_INSERT_ID(expr). Suppose that id is the AUTO_INCREMENT column. To make LAST_INSERT_ID() meaningful for updates, insert rows as follows: 

INSERT INTO table (a,b,c) VALUES (1,2,3) 
    ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), c=3; 
The DELAYED option is ignored when you use ON DUPLICATE KEY UPDATE. 
6

중복으로 col3 만 업데이트하면됩니다. 이것은 정확히 당신이 요구하는 것입니다.

INSERT INTO models (col1, col2, col3) 
VALUES ('foo', 'bar', 'alpha') 
ON DUPLICATE KEY UPDATE col3='alpha'; 
관련 문제