SQL UPDATE或INSERT如果行尚不存在

时间:2016-04-04 15:46:43

标签: php mysql

MySQL的:

"UPDATE FYP_MilestoneNotes SET Notes = '$notes' WHERE UserID = $userID AND MilestoneID = $milestoneID"

当这一行不存在时,我得到了一个错误,如果一个行不存在,我怎么能改变它来插入一个具有相同值的行?

我试过了:

"INSERT INTO FYP_MilestoneNotes SET Notes = '$notes'
                                WHERE UserID = $userID 
                                AND MilestoneID = $milestoneID
                                ON DUPLICATE KEY UPDATE FYP_MilestoneNotes
                                SET Notes = '$notes'
                                WHERE UserID = $userID 
                                AND MilestoneID = $milestoneID
                                "

没有运气

我也尝试过以下建议:

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   在第1行'WHERE UserID = 2 AND MilestoneID = 11 ON DUPLIC'附近

     

INSERT INTO FYP_MilestoneNotes(Notes)VALUES('sdgfdgfd')WHERE   UserID = 2 AND MilestoneID = 11 ON DUPLICATE KEY UPDATE   Notes ='sdgfdgfd'WHERE UserID = 2 AND MilestoneID = 11

2 个答案:

答案 0 :(得分:1)

语法错误,根据docs

        ON DUPLICATE KEY UPDATE FYP_MilestoneNotes
                                ^^^^^^^^^^^^^^^^^^

您无法在on duplicate部分指定表格。

insert也可以 NOT 拥有where条款:

        WHERE UserID = $userID 
            AND MilestoneID = $milestoneID
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---completely illegal.

答案 1 :(得分:0)

您应该运行以下查询:

INSERT INTO FYP_MilestoneNotes (UserID, MilestoneID, Notes) 
VALUES (2, 11, 'sdgfdgfd') 
ON DUPLICATE KEY UPDATE Notes='sdgfdgfd'

您不能使用INSERT .. WHERE

来自MYSQL手册:

INSERT INTO table (a,b,c) VALUES (1,2,3)
    ON DUPLICATE KEY UPDATE c=c+1;
UPDATE table SET c=c+1 WHERE a=1;