mysql一条语句执行有就修改没有就插入的操作

Mysql: Insert or Update in One SQL Statement

Published on Oct 3, 2012 by Jamie Munro

I must say, I really wish I knew about this technique years ago – before I started using frameworks to do a lot of my development.  The effort that was wasted in building separate code and separate logic to deal with inserts vs updates, when all of this time, there is a nice and simple feature built-in to Mysql that does this for us…


 The process is quite straight forward, when I run a standard  INSERT  statement with Mysql, I can provide additional properties for dealing with  DUPLICATE KEY , e.g. the record already exists.

Here is an example:

INSERT INTO `table` (`name`, `created`, `modified`)
VALUES ('Jamie', NOW(), NOW())
ON DUPLICATE KEY
UPDATE `name` = 'Jamie', `modified` = NOW()


Notice how in the  UPDATE  statement I'm only updating the name and modified date.

Another nice example can be used for keeping track of the number of times a tag is used.  Imagine you have a table with a list of tags and their associated count.  You can leverage the above functionality to increase the count each time the tag is used again:

INSERT INTO `tags` (`tag`, `count`, `created`, `modified`)
VALUES ('mysql', 1, NOW(), NOW())
ON DUPLICATE KEY
UPDATE `count` = `count` + 1, `modified` = NOW()


That's it!  No more need to right functionality like:

if ($id == 0) {
// do insert
} else {
// do update
}


For my information, visit Mysql Documentation.



原文地址:http://www.endyourif.com/mysql-insert-or-update-in-one-sql-statement/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值