更新查询以根据不同表中的值更改一个表中列的现有值
Posted
技术标签:
【中文标题】更新查询以根据不同表中的值更改一个表中列的现有值【英文标题】:Update query to change existing values for a column in one table based on values from a different table 【发布时间】:2017-08-05 23:57:57 【问题描述】:对于我的标题含糊不清,我深表歉意,因为我总是很难描述在涉及 SQL 时需要做什么。我正在使用 microsoft access,我总共有 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];
【问题讨论】:
Update query to change existing values for a column in one table based on values from another table的可能重复 为什么 Credits 必须是表,而不是选择查询? 【参考方案1】: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]
);
【讨论】:
JOIN 操作抛出语法错误 由于某种原因,它现在在 UPDATE 语句中抛出语法错误【参考方案2】:您可以尝试使用TEMP
表来存储第二和第三表中的数据;
这样做:
1)创建另一个包含两列的第四个表(即Temp):Student ID
和Credits
;
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
【讨论】:
以上是关于更新查询以根据不同表中的值更改一个表中列的现有值的主要内容,如果未能解决你的问题,请参考以下文章
根据表中另一个现有列的内容更改 SQL Server 中的现有列