Update count column from data in another table

后端 未结 5 1760
南方客
南方客 2020-12-17 21:00

In my DB I have two tables Items(Id, ..., ToatlViews int) and ItemViews (id, ItemId, Timestamp)

In ItemViews table I store all views of an item as they come to the s

5条回答
  •  死守一世寂寞
    2020-12-17 21:22

    I found this question / answer a year after it was written and answered. the answer was okay, but I was after something a bit more automatic. I ended up writing a trigger to automatically recalculate the column when a relevant row in the other table was inserted, deleted or updated.

    I think it's a better solution than running something manually to do the recalculation as there isn't any possibility of someone forgetting to run the code:

    CREATE TRIGGER [dbo].[TriggerItemTotalViews] 
       ON  [dbo].[ItemViews]
       AFTER INSERT, DELETE, UPDATE
    AS 
    BEGIN
    SET NOCOUNT ON;
    
    UPDATE [Items] 
    SET [TotalViews] = 
        (
        SELECT COUNT(id) 
        FROM [ItemViews] 
        WHERE [ItemViews].[ItemId] = [Items].[ItemId]
        )
    WHERE [Items].[ItemId] IN
        (
        SELECT [ItemId] FROM [INSERTED] 
        UNION 
        SELECT [ItemId] FROM [DELETED]
        )
    END
    

提交回复
热议问题