1

私はグーグルでMySqlが私にこのようなことをすることを可能にするという何かを見つけました:

$sql = "IF(EXISTS(SELECT api_key, username FROM credentials WHERE id = 0)) 
    THEN UPDATE credentials SET api_key = ?, username = ? WHERE id = 0 ELSE
    INSERT INTO credentials (api_key, username) VALUES (?, ?) END IF";

これは、クエリがその一部となる関数です。

protected function store_credentials($config_file_path = 'envato_credentials_config.json') {
    $credentials_config = $this->get_envato_config($config_file_path);
    $sql = "INSERT INTO credentials (api_key, username, last_update) VALUES (?, ?, NOW()) ON DUPLICATE KEY UPDATE api_key = values(api_key), username = values(username), last_update = values(last_update)";
    if ($stmt = $this->connect->prepare($sql)) {
        $stmt->bind_param('ss', $credentials_config['API'], $credentials_config['User']);
        $stmt->execute();
        $stmt->close();
    } else {
        return false;
    }
}

私はそのようなことをすることができますか?そして、私はステートメントを明確に理解していますか?これらの2つの列内に値が見つからない場合は、新しい値が挿入されます。それ以外の場合は、更新されるだけですか?

4

2 に答える 2

3

重複キー構文でMySQLを使用できます:

INSERT INTO credentials (api_key, username) VALUES (?, ?)
    ON DUPLICATE KEY UPDATE api_key = values(api_key), username = values(username);
于 2012-04-15T14:33:59.627 に答える
2

mysqlには、これを行うREPLACE構文があります。レコードが存在する場合は更新し(実際には古い行を削除して新しい行を挿入します)、そうでない場合は挿入します。

http://dev.mysql.com/doc/refman/5.0/en/replace.html

13.2.7. REPLACE Syntax
REPLACE [LOW_PRIORITY | DELAYED]
    [INTO] tbl_name [(col_name,...)]
    {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
Or:

REPLACE [LOW_PRIORITY | DELAYED]
    [INTO] tbl_name
    SET col_name={expr | DEFAULT}, ...
Or:

REPLACE [LOW_PRIORITY | DELAYED]
    [INTO] tbl_name [(col_name,...)]
    SELECT ...
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. See Section 13.2.5, “INSERT Syntax”.

REPLACE is a MySQL extension to the SQL standard. It either inserts, or deletes and inserts. For another MySQL extension to standard SQL—that either inserts or updates—see Section 13.2.5.3, “INSERT ... ON DUPLICATE KEY UPDATE Syntax”.

Note that unless the table has a PRIMARY KEY or UNIQUE index, using a REPLACE statement makes no sense. It becomes equivalent to INSERT, because there is no index to be used to determine whether a new row duplicates another.

Values for all columns are taken from the values specified in the REPLACE statement. Any missing columns are set to their default values, just as happens for INSERT. You cannot refer to values from the current row and use them in the new row. If you use an assignment such as SET col_name = col_name + 1, the reference to the column name on the right hand side is treated as DEFAULT(col_name), so the assignment is equivalent to SET col_name = DEFAULT(col_name) + 1.

To use REPLACE, you must have both the INSERT and DELETE privileges for the table.
于 2012-04-15T14:34:47.213 に答える