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;
    }
}

我可以做这样的事情吗?我是否清楚地理解了该语句,如果在这两列中找不到值,则将插入新值,否则只会更新?

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 回答