插入到具有不同列名的重复键中

时间:2014-05-28 10:35:33

标签: mysql insert on-duplicate-key

我有两张表profieltestparametertest

我希望value中的profieltest列使用parametertestuser ID相同且field_id = 2位于profieltest的参数进行更新user。但是,如果field_id中的profieltestparametertest之间的组合不存在,我希望它从CREATE UNIQUE INDEX uniqfield ON profieltest (field_id, user)插入。我尝试使用带有唯一键的重复键语句:profieltest.id,同时INSERT INTO profieltest t1(t1.user, t1.field_id, t1.value) VALUES( id ,t1.user = t2.user, t1.field_id=2, t1.value=t2.parameter) SELECT t2.user, t2.parameter FROM parametertest t2 ON DUPLICATE KEY UPDATE SET t1.value = t2.parameter WHERE t1.User = t2.user AND t1.Field_id = 2 是一个自动增量值。我尝试了以下查询,但它给了我一个错误:

  

1064 - 您的SQL语法出错;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   't1附近(t1.user,t1.field_id,t1.value)VALUES(id,t1.user =   t2.user,t1.field_'在第1行

{{1}}

编辑:添加错误。

1 个答案:

答案 0 :(得分:0)

以下查询对我有用:

INSERT INTO Profieltest ( field_id,  user, value )

SELECT field_id, User,  value
FROM parametertest
    WHERE   
    (field_id = 2
    OR field_id  =  6 
    OR field_id = 7)

On duplicate KEY UPDATE 
profieltest.value=(SELECT t2.value
  FROM parametertest t2
  WHERE t2.field_id =profieltest.field_id AND  t2.user=profieltest.user )