MySQL - 在重复键上 - 例如,那么ELSE不起作用

时间:2016-01-27 17:19:20

标签: mysql sql on-duplicate-key select-case

我想在数据库中插入一个条目(uid,A,B)。如果该条目已经存在,我将使用条件更新“A”和“B”列: (1 =旧条目; [2] =新条目)

A = (B[1] == B[2]) ? A[1] : A[2];
B = B[2] + 1;

我的查询:

INSERT INTO TableName (uid,A,B) 
VALUES (uid,A[2],B[2]) 
ON DUPLICATE KEY 
UPDATE  A= (SELECT CASE B WHEN B[2] THEN A ELSE A[2] END), 
        B= B[2]+1;

Ex1:

Old entry : uid = 1; A = 2; B = 4;
New entry : uid = 1; A = 3; B = 4;
-> Should be: A = 2; B = 5;
But my result: A = 3; B = 5; -> FAIL

Ex2:

Old entry : uid = 1; A = 2; B = 4;
New entry : uid = 1; A = 3; B = 6;
-> A = 3; B = 7; (my code works well in this ex) -> OK

非常感谢。

答案1:删除SELECT键使其正常工作

INSERT INTO TableName (uid,A,B) 
VALUES (uid,A[2],B[2]) 
ON DUPLICATE KEY 
UPDATE  A= (CASE B WHEN B[2] THEN A ELSE A[2] END), 
        B= B[2]+1;

回答p-jairaj

INSERT INTO TableName (uid,A,B) 
VALUES (uid,A[2],B[2]) 
ON DUPLICATE KEY 
UPDATE  A= (IF(B=B[2],A,A[2])), 
        B= B[2]+1;

1 个答案:

答案 0 :(得分:0)

试试这个:

INSERT INTO TableName (uid,A,B) 
VALUES (uid,A[2],B[2]) 
ON DUPLICATE KEY 
UPDATE  A= (IF(B=B[2],A,A[2])), 
        B= B[2]+1;