无法获取“从子查询更新”在 Oracle SQL 中工作的语句
我已经查看了所有内容,但无法弄清楚在匹配客户 ID 时如何根据子查询数据更新表中的列。下面是一些语法,可以让您了解我想要做什么:
UPDATE TableName
SET TableName.Revenue = Z.Revenue
FROM
(
SELECT
CustomerID,
sum(Revenue) as Revenue
FROM
(
SELECT
CustomerID,
Revenue
FROM
TableA
WHERE
CustomerID in TableF
UNION ALL
SELECT
CustomerID,
Revenue
FROM
TableB
WHERE
CustomerID in TableF
)
GROUP BY
CustomerID
) Z
WHERE
TableName.CustomerID = Z.CustomerID
本质上,如果同一个表下的另一个 ID 列与子查询中的 ID 匹配,我希望更新表列。我的目标是避免从子查询创建一个全新的表。任何帮助将不胜感激。谢谢。
I've looked all over, but can't figure out how to update a column in a table based on subquery data when matching on a customer ID. Here's some syntax to give an idea of what I'm trying to do:
UPDATE TableName
SET TableName.Revenue = Z.Revenue
FROM
(
SELECT
CustomerID,
sum(Revenue) as Revenue
FROM
(
SELECT
CustomerID,
Revenue
FROM
TableA
WHERE
CustomerID in TableF
UNION ALL
SELECT
CustomerID,
Revenue
FROM
TableB
WHERE
CustomerID in TableF
)
GROUP BY
CustomerID
) Z
WHERE
TableName.CustomerID = Z.CustomerID
In essence, I'm looking to update a table column if another ID column under the same table matches an ID from a subquery. My goal is to avoid creating a whole new table from the subquery. Any help would be appreciated. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Oracle 不支持 UPDATE 的 FROM 子句。这可行:
另一个选择是使用 dml_expression_table 语法,它基本上类似于 update (select ax, by from a join b on aa = bb) set x = y。但这有点奇怪,需要独特的约束才能发挥作用。
或者您可以仅使用 MERGE 和 UPDATE 部分。仅使用 MERGE 进行 UPDATE 的情况并不常见,但由于 Oracle 支持 ANSI 标准,因此它可以帮助您使用熟悉的语法。
Oracle does not support a FROM clause for an UPDATE. This will work:
Another option is to use the dml_expression_table syntax, which basically looks something like
update (select a.x, b.y from a join b on a.a = b.b) set x = y
. But that's kinda weird and requires unique constraints to work.Or you could use MERGE with only an UPDATE section. It's unusual to use a MERGE for only an UPDATE, but since Oracle supports the ANSI standard it may help you use familiar syntax.
看起来您在这里打破了规范化(在数据库中多次重复相同的数据),这可能会在尝试保持此列正确更新时导致很多问题。假设您了解这一点并且仍然想继续,这应该可行:
我认为问题可能是您的 FROM 子句中没有主表或专门加入到查询中。我没有做很多 Oracle 工作,所以我不太肯定,但如果你用 MS SQL Server 运行它,那将是一个问题。
It looks like you're breaking normalization here (repeating the same data more than once in your database), which is likely to cause a LOT of problems down the road with trying to keep this column properly updated. Assuming that you understand that and still want to proceed, this should work:
I think the problem may be that you don't have the main table in your FROM clause or specifically JOINed into the query. I don't do a lot of Oracle work, so I'm not positive, but that would be a problem if you ran this with MS SQL Server.