如果存在然后更新MySQL

时间:2015-03-04 14:03:26

标签: mysql

我试图更新一行,如果它存在,如果它不存在,那么我想在表中执行插入。 picture.id& picture.picturepath是一个唯一的密钥。我看了一些例子,但我不确定我做错了什么。

我遇到过重复密钥更新,不确定这是否与我想要实现的内容相关。

Error message: 1064- You have an error in your SQL syntax near 'UPDATE picture SET picture.picturecontent = ipicturecontent WHERE picture.id at line 5"


    IF EXISTS( SELECT * FROM picture WHERE picture.id = ipictureid 
    AND picture.picturepath = ipicturepath) THEN

    UPDATE picture 
    SET picture.picturecontent = ipicturecontent
    WHERE picture.id = ipictureid 
    AND picture.picturepath = ipicturepath

    ELSE

    INSERT INTO picture (picture.id, picture.picturecontent,picture.picturepath) VALUES (ipictureid, ipicturecontent, ipicturepath)

2 个答案:

答案 0 :(得分:4)

https://stackoverflow.com/a/10095812/1287480< - 信用到期的信用

INSERT INTO模型(col1,col2,col3) 价值观(' foo',' bar',' alpha') ON DUPLICATE KEY UPDATE col3 =' alpha';

答案 1 :(得分:-1)

不要忘记THENBEGINEND

IF EXISTS( SELECT * FROM picture WHERE id = ipictureid 
    AND picturepath = ipicturepath) 
    THEN
        BEGIN
            UPDATE picture 
               SET picturecontent = ipicturecontent
             WHERE id = ipictureid 
               AND picturepath = ipicturepath
        END;
ELSE
    BEGIN
        INSERT INTO picture (id,
                             picturecontent,
                             picturepath) 
                     VALUES (ipictureid, ipicturecontent, ipicturepath)
    END;
END IF;