更新未按要求运行

时间:2013-06-20 07:28:01

标签: mysql mysql-workbench

我在表格中遇到更新问题。在我的下方,我有更新userdeleted列的标记,我还想更改CurrentTimestamp值的那一行的值,但在SET中再添加一个条件后,我的所有行值更新为当前时间戳。

UPDATE dpuserapplication t1 
LEFT OUTER JOIN temp_userapplication t2
ON t1.userName = t2.userName
AND t1.ApplicationName = t2.ApplicationName
AND t1.groupName = t2.groupName
SET t1.userDeleted = CASE WHEN t2.ID IS NULL THEN 1 ELSE 0 END,
t1.CreatedDate = CURRENT_TIMESTAMP;

1 个答案:

答案 0 :(得分:0)

这是因为LEFT OUTER JOIN会返回dpuserapplication的所有行,除非您指定WHERE子句。由于您没有指定任何修改时间戳的条件,因此会在每一行上修改它。

尝试添加条件:

UPDATE dpuserapplication t1
       LEFT OUTER JOIN temp_userapplication t2
                    ON t1.username = t2.username
                       AND t1.applicationname = t2.applicationname
                       AND t1.groupname = t2.groupname
SET    t1.userdeleted = CASE
                          WHEN t2.id IS NULL THEN 1
                          ELSE 0
                        END,
       t1.createddate = CASE
                          WHEN t2.id IS NOT NULL THEN CURRENT_TIMESTAMP
                          ELSE t1.createddate
                        END;  

请参阅this fiddle

发表评论后,如果您只想更新userdeleted设置为1并且现在设置为0的行:

UPDATE dpuserapplication t1
       LEFT OUTER JOIN temp_userapplication t2
                    ON t1.username = t2.username
                       AND t1.applicationname = t2.applicationname
                       AND t1.groupname = t2.groupname
SET    t1.userdeleted = CASE
                          WHEN t2.id IS NULL THEN 1
                          ELSE 0
                        END,
       t1.createddate = CASE
                          WHEN t2.id IS NOT NULL AND t1.userdeleted = 1 THEN CURRENT_TIMESTAMP
                          ELSE t1.createddate
                        END;  

请参阅this fiddle

在这个小提琴中:

  • u1具有userdeleted = 1,但符合条件。其状态更改为0,日期更新。
  • u2具有userdeleted = 0,并符合条件。其状态设置为0(无更改),但日期未更新。
  • u3不符合条件,没有任何反应。