问题
I am using microsoft access and I have a total of 3 tables: Credits, Orders, and Books which are shown below. I need to create an update query that updates the existing Number of Credits for each student based on the books that they have ordered and the corresponding amount of credits for each book.
For instance, student B-17 starts with 24 credits but after the update query it should change the student's credits to 32.
Credits Table
Student ID Number of Credits
B-17 24
F-59 30
Orders Table
Student ID Book ID
B-17 101
B-17 102
F-59 101
F-59 105
Books Table
Book ID Book Title Credits
101 English I 3
102 Accounting 5
105 Calculus 5
This is what I am trying but I keep getting a syntax error in 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];
回答1:
You can try to use TEMP table for storing your data from the 2nd and 3rd tables; Do like this: 1) create another 4th table (i.e. Temp) with two columns: Student ID and Credits; 2) run this script:
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) Start to Update:
UPDATE Credits c, Temp t set c.[Number of Credits] = c.[Number of Credits] + t.Credits
WHERE c.[Student ID] = t.[Student ID];
4) Save and Finished!
Useful: 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
来源:https://stackoverflow.com/questions/45526753/update-query-to-change-existing-values-for-a-column-in-one-table-based-on-values