2012-06-26 49 views
-1

我想更新一個表。帶有加入和案例條件的SQL更新

我的表結構是:

  • MainTable

    id | status | type | user 
    
  • OtherTable

    id | flag 
    

在這裏,我要更新所有statususer字段MainTable排除在哪裏status='Stop'flagOtherTable沒有設置,例如0,但是怎麼樣?

OtherTable只保留type='EMP'的值。

更新:我想用一個條件檢查更新所有MainTable記錄時type ='EMP'

回答

1

智能答案是@Asif

給出這裏更簡單/備用的方式適合我的要求


`update MainTable 
    set status='someStatus' 
    where 
    status!='Stop' 
    and check_type!='EMP' 

    update MainTable 
    set status='someStatus' 
    from MainTable inner join OtherTable on OtherTable.id=MainTable.id 
    where 
    OtherTable.flag=1` 
0

使用子查詢....

Update MainTable Set user="" where status='STOP' and id in (select id from OtherTable 
where Flag!=0) 
+0

您應該使用'='而不是'in'.... – Tirumudi

+0

ya rty ..但我用'IN,現在和不幸'沒有結果 – RollerCosta

1
Update MT set user='someuser', status = "somestatus" 
FROM MainTable MT 
Join 
(
Select * 
from MainTable MT1 
Join Othertable OT on MT1.Id = OT.Id 
AND OT.Flag = 0 
and MT1.type='EMP' 
Union All 
Select * 
from MainTable MT2 
WHERE MT2.id not in (Select ID FROM Othertable where Flag = 0) 
and MT2.type='EMP' 
) tblOther 
on MT.ID = tblOther.ID 
+0

根據您的要求更改您的條件類型='EMP'。 – Asif