MySQL ON DUPLICATE KEY UPDATE语法错误

时间:2012-10-10 09:27:44

标签: php mysql sql linux

嘿伙计们,我想知道是否有人能在我的sql声明中发现任何错误。我希望它在我的表中插入一条新记录,如果还没有。如果它确实存在,那么只需更新它。我在日期字段中的主键。

这是我在php中出现的声明以及我得到的错误:

INSERT INTO ExtraStats (date, supportStaff, startEmails, endEmails, emailsAnswered) VALUES ('$startDate', '$supportStaff', '$startEmail', '$endEmail', '$emailAnswered') ON DUPLICATE KEY UPDATE (supportStaff, startEmails, endEmails, emailsAnswered) VALUES ('$supportStaff', '$startEmail', '$endEmail', '$emailAnswered')

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(supportStaff, startEmails, endEmails, emailsAnswered) VALUES ('2', '3', '1', '3' at line 1 

2 个答案:

答案 0 :(得分:6)

INSERT INTO ExtraStats (
    DATE
    , supportStaff
    , startEmails
    , endEmails
    , emailsAnswered
    )
VALUES (
    '$startDate'
    , '$supportStaff'
    , '$startEmail'
    , '$endEmail'
    , '$emailAnswered'
    )
    ON DUPLICATE KEY

UPDATE 
        supportStaff = '$supportStaff'
        , startEmails = '$startEmail'
        , endEmails = '$endEmail'
        , emailsAnswered =  '$emailAnswered'

您也可以使用VALUES()函数,因此不会将值传递两次:

    ...
    ON DUPLICATE KEY    
UPDATE 
          supportStaff = VALUES(supportStaff)
        , startEmails = VALUES(startEmails)
        , endEmails = VALUES(endEmails)
        , emailsAnswered = VALUES(emailsAnswered)

答案 1 :(得分:0)

date是一个保留字,用反引号括起来:

INSERT INTO ExtraStats (`date`, supportStaff, startEmails, etc...

此外,ON DUPLICATE KEY UPDATE应该是这样的:

ON DUPLICATE KEY UPDATE supportStaff = '$supportStaff', startEmails = '$startEmail', etc..

您可以查看manual了解其他示例。如果你还没有这样做以避免SQL注入,你还应该考虑对变量进行整理。