2017-08-16 74 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)