我如何在我的SQL数据库中更新此字段?

时间:2009-05-11 06:31:39

标签: tsql sql-update

我有两张桌子。

BoardPosts
BoardPostId INT PK
ModifiedOn DATETIME NULLABLE

BoardComments
BoardCommentId INT PK
BoardPostId INT
CreatedOn DATETIME

董事会帖子有零到多条评论。

如果董事会有评论,我希望将ModifiedOn字段设置为最近的评论日期。否则,只需将其保留为空。

我如何使用TSql执行此操作?

类似......

UPDATE BoardPosts
SET ModifiedOn = CreatedOn
SELECT TOP(1) CreatedOn
FROM BoardPosts a INNER JOIN BoardComments b ON a.BoardPostId = b.BoardPostId

???

2 个答案:

答案 0 :(得分:2)

我认为这会奏效......

UPDATE BoardPosts
SET ModifiedOn = (SELECT MAX(CreatedOn) 
                  FROM BoardComments 
                  WHERE BoardComments.BoardPostId = BoardPosts.BoardPostId)

答案 1 :(得分:0)

我决定考虑评论和未评论的帖子:

update p1 set ModifiedOn = (
select
    max(case when c.CreatedOn is null then p.CreatedOn
    else c.CreatedOn end) as ModDate
from 
    boardposts p
    left outer join BoardComments c on
        p.BoardPostId = c.BoardPostId
where
    p.BoardPostId = p1.BoardPostId
group by p.BoardPostId
)
from
    BoardPosts p1

希望这有帮助!