gpt4 book ai didi

sql - t-sql使用内连接更新多行

转载 作者:行者123 更新时间:2023-12-02 09:36:50 26 4
gpt4 key购买 nike

我尝试同时更新表中的多行列。

我想从另一个具有外键的表中获取要更新的值。

Table Table1:

Id Primary
UserNumber INT


Table Table2
Id Primary
Id_T1 ForeignKey
UserId INT
OrderNumber INT

有人可以帮忙吗?

注意:在表 T2 中,我需要 UserId 值,其中订单号具有最大值。

例如:

Id_T1 UserId OrderNumber 
15 24 1
15 55 2
15 72 3

我想要接收的值是 72。

i have try this:
update T1 set T1.UserNumber = T2.UserId
FROM Table1 AS T1
INNER JOIN Table2 AS T2
ON T1.Id = T2.IdMain
WHERE T1.Id = T2.IdMain
AND T2.OrderNumber = (SELECT MAX(T2.OrderNumber) FROM Table2)

但我收到此错误:

Msg 147, Level 15, State 1, Line 6 An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

最佳答案

您不需要在内部查询中使用别名。试试这个:

UPDATE T1 
SET T1.UserNumber = T2.UserId
FROM Table1 AS T1 INNER JOIN
Table2 AS T2 ON T1.Id = T2.IdMain
WHERE T1.Id = T2.IdMain
AND T2.OrderNumber = (SELECT MAX(OrderNumber) FROM Table2)

关于sql - t-sql使用内连接更新多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24991920/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com