我想知道以下问题:
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一样给statisticstable一个别名来澄清我想要获得UserId的位置?或者有办法吗?
答案 0 :(得分: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)
答案 1 :(得分:0)
试试这个:
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)