2017-08-16 46 views
2

我想了解一下下面的查询:SQL Server:如何在更新语句中使用别名?

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如何知道第二个“用户ID”字段来自从OtherTablestatisticsTable不? 为什么我不能给像stat这样的statisticstable别名来澄清我想要获取该UserId的位置?还是有办法?

+1

这是正常工作?我通常会做一些事情,比如'WHERE o.UserId = statisticsTable.UserId'。 – justiceorjustus

+0

https://stackoverflow.com/questions/4981481/how-to-write-update-sql-with-table-alias-in-sql-server-2008 –

+0

你不能'UPDATE statisticsTable as s' 然后你的子查询中有WHERE o.UserID = s.UserId?我还没有测试过。我从来没有一个需要子查询的UPDATE。 – Cenderze

回答

5

使用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

更新后错过了别名。 :) –

+1

@SeanLange谢谢! –

+0

这是我从未见过的东西。谢谢! –

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)