MySQL How to insert new record or update a field depending on whether it exists?

空扰寡人 提交于 2020-01-04 17:26:13

问题


I am trying to implement a rating system where I keep the following two fields in my db table:

rating (the current rating) num_rates (the number of ratings submitted so far)

UPDATE `mytable`
   SET rating=((rating*num_rates)+$theRating)/num_rates, num_rates=num_rates+1
 WHERE uniqueCol='$uniqueCol'

the variables are from my PHP code.

So, basically sometimes the row with the uniqueCol does not exist in the DB, so how can I do the above statement if the exists and if it doesn't then do something like this:

INSERT INTO `mytable`
   SET rating=$theRating, num_rates=1, uniqueCol=$uniqueCol

回答1:


Have a look at INSERT ... ON DUPLICATE KEY UPDATE.

It should look something like that:

INSERT INTO mytable (rating, num_rates, uniqueCol)
VALUES ($theRating, 1, $uniqueCol)
ON DUPLICATE KEY UPDATE
  rating=((rating*num_rates)+$theRating)/num_rates,
  num_rates=num_rates+1;

Make sure to have a UNIQUE index or PRIMARY KEY on your uniqueCol.



来源:https://stackoverflow.com/questions/2036794/mysql-how-to-insert-new-record-or-update-a-field-depending-on-whether-it-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!