问题
I'm trying to INSERT in my Postgresql database only if my model don't exists. I'm using PDO connection, I try IGNORE and ON DUPLICATE KEY UPDATE but with errors in PDO / syntax.
MY Code:
if(isset($_POST['insertModel'])){
require("includes/connection.php");
$models = $_POST['name'];
$parametros = array($models);
$sth = $dbh->prepare("INSERT INTO models (name) VALUES ( ? )");
$sth->execute($parametros);
if($sth){
header("location: admin.php?model_inserted=1");
}
}
Thanks
回答1:
ON DUPLICATE KEY UPDATE
is MySQL syntax, not PostgreSQL. PostgreSQL doesn't have a simple SQL syntax to do what you want.
But the documentation includes example code for a function that does that.
CREATE TABLE db (a INT PRIMARY KEY, b TEXT);
CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
LOOP
-- first try to update the key
UPDATE db SET b = data WHERE a = key;
IF found THEN
RETURN;
END IF;
-- not there, so try to insert the key
-- if someone else inserts the same key concurrently,
-- we could get a unique-key failure
BEGIN
INSERT INTO db(a,b) VALUES (key, data);
RETURN;
EXCEPTION WHEN unique_violation THEN
-- do nothing, and loop to try the UPDATE again
END;
END LOOP;
END;
$$
LANGUAGE plpgsql;
回答2:
Why not use a try-catch and just catch the duplicate keys? That way you can present the caught duplicates for the user (if you want to).
来源:https://stackoverflow.com/questions/5297045/postgresql-insert-if-specific-row-name-dont-exists