mysql一条语句执行有就修改没有就插入的操作
来源:互联网 发布:国家对于大数据发展 编辑:程序博客网 时间:2024/04/30 01:07
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 KEYUPDATE `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 KEYUPDATE `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/
0 0
- mysql一条语句执行有就修改没有就插入的操作
- mysql一条sql实现没有数据就插入数据有数据则更新数据
- mysql如果有数据就更新,没有数据就插入的方法
- 数据库有就更新,没有就插入
- mysql插入数据时候先检查表中有没有相同的数据如果有就删除原来记录插入,没有就直接插入
- mySql往一个表中增加数据,如果已经有就更新,没有就插入数据
- 数据库--SQL--有就更新,没有就插入
- 对于同一张表中没有记录就插入否则就修改
- mysql如何用一条sql语句实现不存在就插入,存在的话则更新
- mysql使用exists实现没有就插入
- mysql有数据就更新,没数据就插入
- MySql 的ON DUPLICATE KEY UPDATE函数(有记录就更新,没记录就插入)
- 在MySql里面查询有记录,但是调用程序执行就没有记录
- mysql sp_add_Index 先判断有没有索引 没有就添加
- 在C# WebBrowser控件插入JS代码并执行,可以修改js就能对html执行任意操作
- sql语句,oracal更新操作传入参数为对象,判断对象中的字段是否有值,如果有就更新,如果没有就不更新
- 权威数据库有就更新没有就插入 亲测可以
- oracle表中存在数据就修改,没有数据自动添加 的sql语句
- oracle 性能优化操作四:尽量去掉"IN"、"OR"
- VLC 中文路径转码问题
- java 工具下载 myeclipse 10 下载地址
- 关于学习
- Sublime Text如何安装插件
- mysql一条语句执行有就修改没有就插入的操作
- Android cocos2dx HelloCpp代码分析
- Hibernate的fetch
- 单例模式
- 软件推荐
- 使用GDI+模拟directx 3D渲染中的坐标变换
- makefile中的patsubst
- 读书笔记系列之C/C++关键字(一)
- CocoaPods的使用