views:

161

answers:

1

I have a plus/minus system where a user can add one or minus one away from a blog post.

My database (MySQL) table looks like this: userid entry id vote - which is +1 or -1 timeStamp

I have set the timeStamp to default to CURRENT_TIMESTAMP.

I have to methods plus() and minus(). Both do the same thing but one inserts +1 into 'vote' and the other inserts -1. Since (userid,entryid) is the primary key, I am using REPLACE INTO. INSERT INTO brings up a duplication error. INSERT IGNORE doesn't let the user change the vote from +1 to -1

"REPLACE INTO votes(userid, entryid, vote) VALUES(:uid,:eid, -1)";

Ignore the values..

While REPLACE INTO works perfectly, I am ordering by the timestamp, so when someone clicks +1 a second time after voting, it updates the timestamp, which brings it to the top of the list.

Anyone know a solution to this?

ps sorry for the bad title. Couldn't think of a suitable one.

+3  A: 

Using the INSERT ... ON DUPLICATE KEY UPDATE Syntax of MySQL, you could perform the check inline, and only update the timestamp IF the vote actually changed:

INSERT INTO 
  votes 
SET 
  userid = :uid, 
  entryid = :eid, 
  vote = :vote,
  timeStamp = NOW()  /* I'm being explicit here -- you don't need this */
ON DUPLICATE KEY UPDATE 
  vote = :vote, 
  timeStamp = IF(vote = :vote, timeStamp, NOW())
gahooa
you don't need to reference the timestamp column at all since the timestamp is only updated if the row is actually updated. if the vote is the same, then there is no change and the timestamp column is not updated.
longneck