1

我需要更新一个跟踪论坛中“子”帖子数量的列。父帖子和子帖子都存储在同一个表中。架构是:

ForumPosts {
   PostID: bigint,
   ParentFK: bigint, -- if child, this will point to the parent
   AnswerCount: int
   ...
}

如果帖子是子帖子,则parentFK指向ForumPosts表中的不同记录。

我想做这样的事情:

UPDATE ForumPosts 
SET AnswerCount = (
        SELECT COUNT(PostID) 
        FROM ForumPosts 
        WHERE ParentFK = ???
)

...但它不起作用,因为 SELECT 需要引用正在更新的记录,我不知道该怎么做。

4

2 回答 2

3

在子查询中使用别名。这样,您可以轻松地指定字段是属于子查询还是属于主更新查询。

UPDATE ForumPosts 
SET AnswerCount = (
        SELECT COUNT(sub.PostID) 
        FROM ForumPosts sub
        WHERE sub.ParentFK = ForumPosts.PostID
)
于 2012-12-21T07:34:14.810 回答
3

你可以这样做:

UPDATE f
SET f.AnswerCount = t.Counts
FROM ForumPosts f
INNER JOIN
(
   SELECT ParentFk, COUNT(PostID) counts
   FROM ForumPosts
   GROUP BY ParentFK
) t ON f.PostId = t.ParentFK;

但是,如果这些论坛帖子存储为层次结构,在这种情况下,您可以使用递归 CTE,如下所示:

DECLARE @parentID INT = 1;

WITH CTE
As
(
  SELECT PostId, ParentFK
  FROM ForumPosts
  WHERE parentFK = @parentId
  UNION ALL
  SELECT p.PostId, p.ParentFK
  FROM CTE c
  INNER JOIN ForumPosts p ON c.postId = p.parentFK
), WithCounts
AS
(
  SELECT ParentFk, Count(PostId) Counts
  FROM CTE
  GROUP BY ParentFK
)
UPDATE f
SET f.AnswerCount = t.Counts
FROM ForumPosts f
INNER JOIN WithCounts t ON f.PostId = t.ParentFK;

SQL 小提琴演示

于 2012-12-21T07:34:37.503 回答