这样的SQL查询是否存在?

时间:2012-04-15 14:30:47

标签: php mysql sql

我在google上找到了一些说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 个答案:

答案 0 :(得分:3)

你可以使用MySQL的on duplicate key syntax

INSERT INTO credentials (api_key, username) VALUES (?, ?)
    ON DUPLICATE KEY UPDATE api_key = values(api_key), username = values(username);

答案 1 :(得分: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.