Merbin Jo
Merbin Jo

Reputation: 1209

How to insert and update for view count in 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

Upvotes: 2

Views: 462

Answers (2)

Passionate Coder
Passionate Coder

Reputation: 7294

Try this

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

VALUES(col_name) in the ON DUPLICATE KEY UPDATE clause refers to the value of col_name that would be inserted

Upvotes: 1

Boris Schegolev
Boris Schegolev

Reputation: 3701

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

Upvotes: 1

Related Questions