MySQL如果存在,则插入或执行其他操作 [英] MySQL If exsists insert into or else do something else

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

问题描述

在将条件插入MySQL时遇到一些困难.我一直在尝试创建一个查询,该查询将遍历所有标题为email的列,如果存在,我想执行以下操作: 如果存在电子邮件,我希望它使列的现有值正确,并向其中添加php变量$ correct.但是,如果电子邮件不存在,那么我希望它向$ mail列中添加一个值为$ email的新记录,并向right列中添加$ 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'

另请参阅我对其他堆栈溢出问题的回答:

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆