2011-12-30 82 views
1

我有兩個表請告知SQL更新問題

表AID, State, Value

1 England 20 
2 France 50 
3 USA  40 
4 ........ 
5 ........ 

表BID, username, age, stateID

1 John 15 1 
2 Adam 20 2 
3 Jane 40 3 
4 Scott 50 1  
5 Edwin 60 2 
6 Alex 20 3 
7 Olsen 30 1 
8 ........... 
9 ........... 
SQL數據庫3210

我需要的是通過設定年齡爲所有用戶更新TableB

  • England爲20
  • France爲50

等等...

回答

3
update tableB 
set age = (select tableA.value from tableA where tableA.StateID=TableB.id) 
2

我喜歡這樣的形式如下:

update b set 
    age = a.value 
from tableB b 
join tableA a on a.id = b.stateId 

,因爲你可以把它寫這樣(最後在SQL Server Management Studio中):

update b set 
    age = a.value 
--select b.age, a.value, b.*, a.* 
from tableB b 
join tableA a on a.id = b.stateId 

再突出部分從select ...到查詢的末尾並執行它(F5)檢查什麼你會改變(價值之前和之後)。

+0

非常感謝:) – RMohammed 2011-12-30 10:15:28