2012-10-10 73 views
3

嘿傢伙我想知道如果任何人都可以發現我的SQL語句中的任何錯誤。我希望它能在我的表格中插入一條新的記錄,如果其中一條不存在的話。如果它確實存在,那就更新它。我在日期字段中的主鍵。MySQL在重複密鑰更新語法錯誤

這裏是我的發言,因爲它出現在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 

回答

5
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) 
+0

你先生是個天才! 太棒了! 謝謝! –

0

date是一個保留字,用反引號括起來:

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

此外,ON DUPLICATE KEY UPDATE應該是這樣的:

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

您可以檢查manual其他例子。如果您還沒有執行這些操作以避免SQL注入,您還應該考慮對變量進行saniziting。

+0

這並不是說一點它在抱怨它的下位: 對重複密鑰更新(supportStaff,startEmails,endEmails,emailsAnswered)VALUES( '$ supportStaff', '$ startEmail', '$ endEmail', '$ emailAnswered') 第一位通過它自己的重複密鑰位罰款。 –

+0

@Luke CheerfulPlum步伐我已經更新了我的答案:) – tradyblix