i have two tables.
我有两张桌子。
BoardPosts
BoardPostId INT PK
ModifiedOn DATETIME NULLABLE
BoardComments
BoardCommentId INT PK
BoardPostId INT
CreatedOn DATETIME
A board post has zero to many comments.
董事会帖子有零到多条评论。
I wish to set the ModifiedOn
field to be the most recent comment date, if the board has a comment. Otherwise, just leave it null.
如果董事会有评论,我希望将ModifiedOn字段设置为最近的评论日期。否则,只需将其保留为null。
How do i do this, using TSql ?
我怎么做这个,使用TSql?
something like ...
就像是 ...
UPDATE BoardPosts
SET ModifiedOn = CreatedOn
SELECT TOP(1) CreatedOn
FROM BoardPosts a INNER JOIN BoardComments b ON a.BoardPostId = b.BoardPostId
???
2 个解决方案
#1
I think this will work...
我认为这会奏效......
UPDATE BoardPosts
SET ModifiedOn = (SELECT MAX(CreatedOn)
FROM BoardComments
WHERE BoardComments.BoardPostId = BoardPosts.BoardPostId)
#2
I decided to take into account both commented and uncommented posts:
我决定考虑评论和未评论的帖子:
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
Hope this helps!
希望这可以帮助!
#1
I think this will work...
我认为这会奏效......
UPDATE BoardPosts
SET ModifiedOn = (SELECT MAX(CreatedOn)
FROM BoardComments
WHERE BoardComments.BoardPostId = BoardPosts.BoardPostId)
#2
I decided to take into account both commented and uncommented posts:
我决定考虑评论和未评论的帖子:
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
Hope this helps!
希望这可以帮助!