douhensheng1131
2016-09-13 06:54
浏览 72
已采纳

如何在mysql中插入和更新视图计数?

How can I count the view value in mysql table. If the first user like the post in the viewdetails table insert a row with Counts column value 1, If the next user like the post just update the Counts column(previous Counts value +1) ,without check anything.
So I tried and take a sytax from internet Duplicate Key, but I don't know how to used it.

I tried below

INSERT INTO viewdetails
  (PostID,Counts)
VALUES
  (1, 1)
ON DUPLICATE KEY UPDATE
  Counts     = VALUES(Counts)+1

The above example is working like below
1st execution Insert Counts => 2

2nd execution Update Counts => 2

3rd execution Update Counts => 2


But I need like below
1st execution Insert Counts => 1

2nd execution Update Counts => 1+1

3rd execution Update Counts => 2+1

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanmu2015 2016-09-13 06:57
    已采纳

    VALUES(Counts) refers to the input, not the value in the table. Try something like:

    INSERT INTO viewdetails
      (PostID,Counts)
    VALUES
      (1, 1)
    ON DUPLICATE KEY UPDATE
      Counts = Counts+1
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题