2013-06-20 67 views
0

我在更新表中有問題。在我的下面我有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; 
+0

我只想更新列userdeleted設置爲0而不是所有行的行。 –

回答

0

這是因爲在LEFT OUTER JOIN的,除非你指定一個WHERE子句返回的dpuserapplication所有行。由於您沒有指定修改時間戳的任何條件,因此它會在每一行上進行修改。

嘗試增加一個條件:

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不符合條件,沒有任何反應。
+0

我們可以像在SET中使用UserDeleted一樣使用大小寫條件,我是mysql新手,並且對此沒有太多知識 –

+0

是的,AFAIK沒有問題。 –

+0

但是這是行不通的。所有的行中獲取相同的時間戳AFTE運行此腳本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 NULL THEN CURRENT_TIMESTAMP END; –