POSTGRESQL INSERT if specific row name don't exists !

99封情书 提交于 2020-01-06 15:18:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!