2012-12-12 93 views
0

道歉如果標題沒有準確地描述問題(它可能沒有)。我有以下兩個表: -如何在交叉引用另一個表時更新記錄?

tLiveTable:

PieceID  LocationRef 
------------------------ 
100    5 

tPieceTable:

ID BatchNo  PieceNumber 
------------------------------ 
50 ABC   X1 
100 ABC   X1 

我怎樣才能更新LocationRef那塊在tLiveTable只給出BatchNo和PieceNo?

我已嘗試以下步驟:在tPieceTable

UPDATE tLiveTable 
SET LocationRef = 'blabla unimportant' 
WHERE 
PieceID = (SELECT ID FROM tPieceTable WHERE (BatchNo = 'ABC') AND (PieceNo = 'X1')) 

但可以有多個條目具有相同BatchNo和PieceNo。我只想從tPieceTable中檢索ID,它的ID現在是tLiveTable中的ID。

我真的應該使用INNER JOIN嗎?

回答

1

您的查詢將工作SELECT ID FROM tPieceTable WHERE (BatchNo = 'ABC') AND (PieceNo = 'X1')返回多個ID

試試這個;

UPDATE L SET LocationRef = 'blabla unimportant' 
FROM tLiveTable L JOIN tPieceTable P 
    ON L.PieceID = P.ID 
WHERE (P.BatchNo = 'ABC') AND (P.PieceNo = 'X1') 

或者使用IN=

UPDATE tLiveTable 
SET LocationRef = 'blabla unimportant' 
WHERE 
PieceID IN (SELECT ID FROM tPieceTable WHERE (BatchNo = 'ABC') AND (PieceNo = 'X1'))