简体   繁体   中英

How to understand if MySQL updated or inserted

This seems like such a simple problem but Google cannot seem to find much on the topic.

For caching reasons I want to run a query to let a user like something:

INSERT INTO tbl_review_vote (user_id,review_id,vote) VALUES(:uid,:rid,:vote) ON DUPLICATE KEY UPDATE vote=:vote

But then understand from the server response whether or not the like was inserted or updated so that I can pre-aggregate a likes to the user review record.

Is there a good way of doing this?

With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row and 2 if an existing row is updated. You could then look at the difference between mysql's LAST_INSERT_ID() and your API's last_insert_id to ascertain whether it was an insert or an update.

An alternative way to see what it was, is by adding an update_count column which increments with your query: update_count = update_count + ; , or alternatively, a timestamp without ON UPDATE CURRENT_TIMESTAMP

Try these php functions:

mysql_affected_rows() or mysqli_affected_rows()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM