MySQL如何根据其是否存在来插入新记录或更新字段?

编程入门 行业动态 更新时间:2024-10-22 16:22:05
本文介绍了MySQL如何根据其是否存在来插入新记录或更新字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试实施一个评分系统,该数据库将以下两个字段保留在我的数据库表中:

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

等级(当前等级) num_rates(到目前为止已提交的评分数)

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'

变量来自我的PHP代码.

the variables are from my PHP code.

因此,基本上,有时在数据库中不存在带有uniqueCol的行,因此,如果存在,我该如何做上述声明,如果不存在,则该做以下事情:

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

推荐答案

看看插入...在重复的密钥更新上.

它看起来应该像这样:

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;

确保uniqueCol上有UNIQUE index或PRIMARY KEY.

更多推荐

MySQL如何根据其是否存在来插入新记录或更新字段?

本文发布于:2023-10-25 08:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1526481.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   是否存在   MySQL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!