1

I have a table with columns id, user_id, post_id, like, views. When a user click the Like button, a row will be added to the table with the corresponding user_id and post_id, and like will be set to 1. If the row already exist and the like column already is 1, nothing will happen.

When the user visits a particular page, a row will be added to the table with the corresponding user_id and post_id, and view will be set to 1. However if the row already exist, the value in view will be incremented.

Problem: I tried using INSERT INTO mytable ... ON DUPLICATE KEY UPDATE like = 1, but the primary key of the table is id and not user_id or post_id. If I set the primary key to either user_id or post_id, there will be a problem because the row will only be duplicated if there exist a row with the same user_id and post_id.

In this situation, how should the query be built?

Or will a better situation be to split the table into 2 tables, one for likes and 1 for views. If this is the case, I still need to make the row unique based on both user_id and post_id columns.

Or do multiple SQL queries?

Please advise, thanks!

4

2 回答 2

1

I would suggest that you have a table for likes, and then in whatever table that you keep posts in, you add a row for views. So whenever this post is viewed, you simply update the view value for that post to view = view + 1.

Now to address the problem that you outlined about the primary keys, you should note that you can use a unique key in that scenario, which can apply to multiple columns and would fix the issue that you ran into. So for example if in your scenario you had a unique key that encompassed both the userid and postid, your database would not allow for two different rows in that table with the same userid and postid.

So for future reference, use a unique key if you need to :)

于 2012-07-21T21:05:22.893 回答
0
  1. discard the id as primary key
  2. use two tables
  3. make primary key on (user_id, post_id)
  4. when handle insert like, do a insert ignore
  5. when handle insert view, do a insert .. duplicate key update view = view+1
于 2012-07-21T20:32:58.417 回答