我在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;
}
}
我能做那样的事吗?我是否清楚地理解了语句,如果在这两列中没有找到值,那么将插入新值,否则它将只更新?
最佳答案
你可以使用MySQL的on duplicate key syntax:
INSERT INTO credentials (api_key, username) VALUES (?, ?)
ON DUPLICATE KEY UPDATE api_key = values(api_key), username = values(username);
关于php - 是否存在这样的SQL查询?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10162903/