我有一个表(TABLE1),它有4列:
UID | PID | VALUE1 | VALUE2
我有另一个SQL语句(STMT)从一些其他表返回3列:
UID | PID | VALUE1
现在这里是我想要更新TABLE1的条件:
首先,将STMT中的UID和PID对与TABLE1中的那些对比,
对于不在TABLE1中的所有新UID和PID对,将新行从STMT插入到TABLE1中,设置TABLE1.VALUE2 = 0(我已经完成了这一行)
对于STMT和TABLE1中的现有UID和PID对,执行:
一个。如果TABLE1.VALUE2> 0,更新TABLE1.VALUE1 = STMT.VALUE1
湾如果TABLE1.VALUE2 = 0并且如果TABLE1.VALUE1!= STMT.VALUE1,则更新TABLE1.VALUE1 = STMT.VALUE1,否则不执行任何操作。
我无法提出条件2的解决方案。感谢所有帮助!
答案 0 :(得分:2)
UPDATE (
SELECT table1.UID
,table1.PID
,table1.value1 AS table1_value1
,table1.value2 AS table1_value2
,stmt.value1 AS stmt_value1
FROM table1
INNER JOIN (SELECT ? AS UID
,? AS PID
,? AS value1
FROM whatever) stmt
ON stmt.UID = table1.UID
AND stmt.PID = table1.PID
) x
SET x.table1_VALUE1 = CASE WHEN (x.table1_VALUE2 > 0) OR
(x.table1_VALUE2 = 0 AND x.table1_VALUE1 <> x.stmt_VALUE1)
THEN x.stmt_VALUE1
ELSE x.table1_VALUE1
END