SQL Server:如何在update语句中使用别名?

Ste*_*ens 4 sql sql-server sql-update

我想知道以下查询:

   UPDATE statisticsTable
   SET Value = (select count(*) 
                FROM OtherTable o
                WHERE o.UserId = UserId ) <-- this is the part that concerns me
   WHERE id in (1,2,3) 
Run Code Online (Sandbox Code Playgroud)

SQL Server如何知道第二个"UserId"字段来自statisticsTable而不是来自OtherTable?为什么我不能像stat一样给statisticstable一个别名来澄清我想要获得UserId的位置?或者有办法吗?

Zoh*_*led 9

SQL Server支持使用连接进行更新.
这意味着您可以像这样编写查询:

UPDATE s
SET Value = d.NumOfRows
FROM statisticsTable s
INNER JOIN
(
     SELECT UserId, COUNT(*) As NumOfRows
     FROM OtherTable
     GROUP BY UserId
) d ON s.UserId = d.UserId
WHERE id in (1,2,3) 
Run Code Online (Sandbox Code Playgroud)