I have 2 tables with one-to-one relationship:
post_views table
___________________________________
| | | |
| id | post_id | views |
|________|_____________|___________|
posts table
__________________________________________
| | | | |
| id | title | text | .. |
|________|___________|__________|_________|
post_id
from post_views
table is joined with id
from posts
table.
The id
in both tables is primary and auto incremented, And the post_id
is unique.
Here is a screenshot of the indexes for post_views
:
https://prnt.sc/k6no10
Each post should has only one row in post_views
table.
I run this query to insert a new row or increase the views, If that post_id
exists:
INSERT INTO post_views (`post_id`, `views`) VALUES (1, 1) ON DUPLICATE KEY UPDATE `views` = `views`+1
It's executed successfully and a new row is inserted:
____________________________________
| | | |
| id | post_id | views |
|__________|_____________|___________|
| | | |
| 1 | 1 | 1 |
| | | |
|__________|_____________|___________|
Then when I run the same query again to increase the views, I get a success message saying that 2 rows inserted
and the row is now:
____________________________________
| | | |
| id | post_id | views |
|__________|_____________|___________|
| | | |
| 1 | 1 | 2 |
| | | |
|__________|_____________|___________|
And that's what I want, but if I run the query with a new post_id
:
INSERT INTO post_views (`post_id`, `views`) VALUES (2, 1) ON DUPLICATE KEY UPDATE `views` = `views`+1
I get that:
____________________________________
| | | |
| id | post_id | views |
|__________|_____________|___________|
| | | |
| 1 | 1 | 2 |
|__________|_____________|___________|
| | | |
| 3 | 2 | 1 |
|__________|_____________|___________|
The id
is 3 instead of 2, So each time I run the query with the same post_id
is like I'm inserting a new row with an id.
So if I run the query with post_id = 3
three times, The news id will be 7.
Is that's normal?