2011-08-16 56 views
1

我試圖做一個更新,保存舊值,如果新的空語法錯誤,SQL查詢是的MySQL與COALESCE()重複鍵更新插入調用java中

INSERT INTO scheme (id,type) 
VALUES (1,1) ON DUPLICATE KEY 
UPDATE scheme 
SET type=COALESCE(1,type) 
WHERE id=1 

錯誤文字是

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'SET type=COALESCE(1,type) 
WHERE id=1' at line 4 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) 
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513) 
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406) 
    at com.mysql.jdbc.Util.getInstance(Util.java:381) 
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030) 

我猜想,這就是明顯的東西我失蹤,但我無法弄清楚:(

回答

2

你永遠需要一個ON DUPLICATE KEY查詢WHERE(和它的sh應該總是在MySQL中破解) - 衝突線已經被發現,並且由於它們不能有兩個,所以你必須更新那個。隱含WHERE

試試這個:

INSERT INTO scheme (id,type) 
VALUES (1,1) ON DUPLICATE KEY 
UPDATE scheme 
SET type=COALESCE(1,type) 
+0

我幾乎可以肯定,在互聯網上的某個地方,我看到的'對重複KEY'的例子,也有'WHERE'。但是,儘管如此,我檢查了這種方式是否能正常工作,但不幸的是,這並不是。還是一樣的'檢查手冊<...>的正確語法在第4行'SET type = COALESCE(1,type)'附近使用 – idji