使用coalesce()在重复键更新上插入MySQL会在java中调用语法错误

时间:2011-08-16 17:03:29

标签: java mysql syntax-error

我正在尝试进行更新,如果新值为NULL,则保存旧值,SQL查询

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)

我想这只是我想念的东西,但我无法弄清楚:(

1 个答案:

答案 0 :(得分:2)

你永远不需要在WHERE查询中ON DUPLICATE KEY(并且它应该总是在MySQL中断) - 已经找到冲突的行,并且由于不能有两个,你必须更新那个。隐含WHERE

请改为尝试:

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