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 存在插入或执行其他操作


- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- SQL 临时表问题 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01