Domanda

Ho due tabelle.

BoardPosts
BoardPostId INT PK
ModifiedOn DATETIME NULLABLE

BoardComments
BoardCommentId INT PK
BoardPostId INT
CreatedOn DATETIME

Un post consiglio ha zero a molti commenti.

Vorrei impostare il ModifiedOn campo di essere la più recente data di commento, se la scheda ha un commento. In caso contrario, basta lasciare nulla.

Come faccio a fare questo, utilizzando TSQL?

qualcosa di simile ...

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

???

È stato utile?

Soluzione

Credo che questo funzionerà ...

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

Altri suggerimenti

Ho deciso di prendere in considerazione sia i messaggi commentati e non commentate:

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

Spero che questo aiuti!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top