4

我想知道是否有人可以在我的 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 
4

2 回答 2

7
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)
于 2012-10-10T09:28:21.197 回答
0

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

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

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

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

您可以查看手册以获取其他示例。如果您还没有这样做,您还应该考虑对变量进行清理以避免 SQL 注入。

于 2012-10-10T09:31:02.503 回答