创建一个mysql记录(如果不存在),否则更新它 [英] create a mysql record if it doesnt exist, else update it

查看:148
本文介绍了创建一个mysql记录(如果不存在),否则更新它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想修改此MySQL查询以仅在该行不存在时才插入该行.否则,我想更新现有的行.

I would like to modify this MySQL query to insert the row only if it does not exist. Otherwise, I would like to update the existing row.

<?php
$query = mysql_query("UPDATE hqfjt_email_history SET datesent = ['datesent'],emailformname = ['emailformname'],leadname = ['leadname']
WHERE emailformname = ['emailformname'] AND leadname = ['leadname']") or die(mysql_error());
?>

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~ 编辑>>

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ EDIT >>

这是正确的吗?

INSERT INTO hqfjt_email_history datesent = ['datesent'],emailformname =     ['emailformname'],leadname = ['leadname'] ON DUPLICATE KEY UPDATE hqfjt_email_history SET     datesent = ['datesent'],emailformname = ['emailformname'],leadname = ['leadname']
WHERE emailformname = ['emailformname'] AND leadname = ['leadname']

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我已经尝试了上面的方法并得到了错误: 您的SQL语法有误;检查与MySQL服务器版本相对应的手册,以在第1行的'datesent = ['datesent'],emailformname = ['emailformname'],leadname = ['leadname'附近使用正确的语法

I have tried the above and get the error : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'datesent = ['datesent'],emailformname = ['emailformname'],leadname = ['leadname'' at line 1

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

更新! 好的,我尝试了这个,它创建了ok的记录:

UPDATE ! Ok, I tried this and it creates the record ok :

但是,如果我这样做,则什么也没有发生,什么也没有更新或创建???? :

If I do this though, nothing happens, nothing gets updated or created ???? :

<?php
$query = mysql_query("
INSERT INTO hqfjt_email_history (id, leadname, emailformname, datesent)
VALUES
('$_POST[id]','$_POST[leadname]','$_POST[emailformname]','$_POST[datesent]') ON         DUPLICATE KEY UPDATE hqfjt_email_history (datesent) VALUES ('$_POST[datesent]')     WHERE id = '$_POST[id]'");
?>

推荐答案

还有将更新现有行或创建一个新行(如果不存在),其语法类似于INSERT.

Which will update the existing row or will create a new one if it doesn't exist, also the syntax is similar to INSERT.

它的作用完全与INSERT ... ON DUPLICATE KEY UPDATE的作用相同,但是我认为这种方法更加优雅.

It does exactly what INSERT ... ON DUPLICATE KEY UPDATE does, but I think this approach is more elegant.

这篇关于创建一个mysql记录(如果不存在),否则更新它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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