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 存在插入或执行其他操作
基础教程推荐
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 无法解决整理冲突 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
