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

hyrbngr7  于 2022-11-28  发布在  SQL Server
关注(0)|答案(3)|浏览(213)

我想知道以下查询:

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)

SQL Server如何知道第二个“UserId”字段来自statisticsTable而不是OtherTable?为什么我不能给予统计表一个别名,如“stat”,以明确我想从哪里获得该UserId?或者有什么方法吗?

kknvjkwl

kknvjkwl1#

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)
pieyvz9o

pieyvz9o2#

试试这个:

UPDATE s
   SET Value = x.cnt
from statisticsTable s
 outer apply (select count(*) as cnt
                FROM OtherTable o
                WHERE o.UserId = s.UserId ) x
WHERE s.id in (1,2,3)
xtupzzrd

xtupzzrd3#

您正在更新的数据表不允许使用别名,但您可以正常方式使用数据表名称:

UPDATE statisticsTable
SET Value = (select count(*) 
            FROM OtherTable o
            WHERE o.UserId = statisticsTable.UserId ) 
WHERE id in (1,2,3)

相关问题