2017-08-05 70 views
-1

對於我的標題含糊不清,表示抱歉,因爲我總是很難描述涉及SQL時需要完成的操作。我使用微軟訪問,我總共有3個表格:Credits,Orders和Books,如下所示。我需要創建一個更新查詢,根據他們訂購的書籍以及每本書的相應信用額度更新每個學生的現有信用數量。根據不同表中的值更新查詢以更改一個表中列的現有值

例如,學生B-17與24個學分啓動,但在更新查詢後,應該改變學生的學分32

積分表

Student ID Number of Credits 
B-17   24 
F-59   30 

訂單表

Student ID Book ID 
B-17   101 
B-17   102 
F-59   101 
F-59   105 

書籍表

Book ID Book Title Credits 
101  English I  3 
102  Accounting 5 
105  Calculus  5 

這是我正在嘗試,但我不斷收到Access中的語法錯誤。

UPDATE Credits c 
SET [Number of Credits] = [Number of Credits] + (SELECT SUM(Credits) 
FROM Orders o, Books b ON 
o.[Book ID] = b.[Book ID] WHERE 
c.[Student ID] = o.[Student ID]) 
WHERE c.[Student ID] = o.[Student ID]; 
+0

[更新查詢以基於另一個表中的值更改一個表中列的現有值]的重複(https://stackoverflow.com/questions/45526753/update-query-to-change - 現有值列爲單一表 - 基於值) – Gustav

+0

爲什麼Credits必須是表格,而不是選擇查詢? – tahwos

回答

0

您的逗號爲ON。您可以嘗試:

UPDATE Credits as c INNER JOIN 
     (SELECT o.[Student ID], SUM(b.Credits) as Credits 
     FROM Orders as o INNER JOIN 
      Books as b 
      ON o.[Book ID] = b.[Book ID] 
     GROUP BY o.[Student ID] 
     ) ob 
     ON c.[Student ID] = o.[Student ID] 
    SET c.[Number of Credits] = c.[Number of Credits] + ob.Credits; 

我經常在使用MS Access時遇到連接語法問題。相反:

UPDATE Credits 
    SET [Number of Credits] = [Number of Credits] + 
           (SELECT SUM(b.Credits) as Credits 
           FROM Orders as o INNER JOIN 
            Books as b 
            ON o.[Book ID] = b.[Book ID] 
           WHERE o.[Student ID] = Credits.[Student ID] 
           ); 
+0

它爲JOIN操作引發語法錯誤 –

+0

由於某種原因,它現在在UPDATE語句中引發語法錯誤 –

0

你可以嘗試使用TEMP表從第二和第三表中存儲數據; 這樣做: 1)用兩列創建另一個第4個表格(即Temp):Student IDCredits; 2)運行此腳本:

SELECT o.[Student ID], sum (b.Credits) as Credits INTO Temp FROM books b INNNER JOIN orders o on b.[Book ID] = o.[Book ID] GROUP BY o.[Student ID];

3)開始更新:

UPDATE Credits c, Temp t set c.[Number of Credits] = c.[Number of Credits] + t.Credits WHERE c.[Student ID] = t.[Student ID];

4)保存並完成!

有用的:1)"Operation must use an updateable query" error in MS Access; 2)MS Access database (2010) how to create temporary table/procedure/view from Query Designer

相關問題