数据库需要单独建统计字段吗?

视频表

create table video (
    video_id    bigint not null,
)

用户给视频点赞表

create table video_favor (
    user_id     bigint not null ,
    video_id    bigint not null ,
)

如果要统计video的点赞量
应该直接计算select count(*) from video_favor where video_id=?
还是单独给video建一个字段favor_count,每次点赞都主动update+1

  • 视频可以加个点赞数,方便后续获取,查点赞表有些多余了。(另外最好定时,稽核一下 点赞数 和点赞表数据是否一致;当然你如果能够保证点赞表和点赞数是事物一致,那可以不管)
  • 如果你要知道都有那些用户点赞,才用到点赞表。

加一个字段好一点,因为会提高查询效率。