MySQL If exsists insert into or else do something else(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 存在插入或执行其他操作
基础教程推荐
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01