MySQL If 存在插入或执行其他操作

MySQL If exsists insert into or else do something else(MySQL If 存在插入或执行其他操作)

本文介绍了MySQL If 存在插入或执行其他操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将条件放入 MySQL 时遇到了一些困难.我一直在尝试创建一个查询,它将遍历所有标题为电子邮件的列,如果它存在,我想做这样的事情:如果存在电子邮件,我希望它采用正确的列的现有值并将 php 变量 $correct 添加到它.但是,如果电子邮件不存在,那么我希望它将值 $email 的新记录添加到列 email 中,并将 $correct 添加到列中.任何帮助将不胜感激.
以下是我拥有和不工作的内容:

I'm having some difficulty putting a conditional into MySQL. I've been trying to create a query that will go through all of the column titled email and if it exists I want to do something like this: If an email exists I want it to take the existing value of the column correct and add the php variable $correct to it. But if an email does not exist then I want it to add a new record with the values $email into the column email and $correct into column correct. Any help would be greatly appreciated.
Here's what I have and does not work:

IF  (SELECT * FROM facebookqs WHERE email = '$email' > 0)
UPDATE facebookqs SET correct = correct + '$correct' where email ='$email' 
Else
Insert into facebookqs (email, correct) VALUES ('$email', '$correct')

推荐答案

假设 email 有一个 UNIQUE 约束,你应该使用 插入 ... 在重复密钥更新

Assuming email has a UNIQUE constraint, you should use INSERT ... ON DUPLICATE KEY UPDATE

INSERT INTO facebookqs (email, correct) VALUES ('$email', '$correct')
ON DUPLICATE KEY UPDATE correct = correct + '$correct'

另请参阅我对其他 Stack Overflow 问题的回答:INSERT IGNORE vs INSERT … ON DUPLICATE KEY UPDATE

See also my answer for this other Stack Overflow question: INSERT IGNORE vs INSERT … ON DUPLICATE KEY UPDATE

这篇关于MySQL If 存在插入或执行其他操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:MySQL If 存在插入或执行其他操作

基础教程推荐