2012-04-10 19 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-データからmysqlへの自動増分プライマリキー) – blackandorangecat

答えて

29

方法について置換え:

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

col1が主キーであると仮定し、値 'foo'を持つ行がすでに存在する場合、他の2つの列を更新します。それ以外の場合は、新しい行が挿入されます。

+0

の問題'replace'はエントリが存在することを前提としています。しかし、この使用法は、両方を挿入または更新しようとしています。 – kasavbere

+1

名前が正しくありません。エントリが存在するとはみなされません。 MySQLのドキュメントから: "REPLACEはINSERTと全く同じように動作します。ただし、テーブルの古い行がPRIMARY KEYまたはUNIQUEインデックスの新しい行と同じ値を持つ場合、新しい行が挿入される前に古い行が削除されます。 " – bobwienholt

+0

私はそれを知らなかった。あなたに投票してください - 私は今日何か新しいことを学びます! – kasavbere

6

あなたは "DUPLICATE KEY UPDATE INSERT ... ON" を使用しようとすることができ、構文

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'; 
関連する問題