Home  >  Article  >  Database  >  MySQL: ON DUPLICATE KEY UPDATE 用法

MySQL: ON DUPLICATE KEY UPDATE 用法

WBOY
WBOYOriginal
2016-06-07 14:54:491197browse

使用该语法可在插入记录的时候先判断记录是否存在,如果不存在则插入,否则更新,很方便,无需执行两条SQL 无 INSERT INTO osc_visit_stats(stat_date,type,id,view_count) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE view_count=view_count+?-- osc_visit_st

使用该语法可在插入记录的时候先判断记录是否存在,如果不存在则插入,否则更新,很方便,无需执行两条SQL
INSERT INTO osc_visit_stats(stat_date,type,id,view_count) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE view_count=view_count+?

-- osc_visit_stats 表有复合主键 (stat_date,type,id) 
INSERT INTO osc_space_visit_records(space,user,visit_count,ip,visit_time) VALUES(?,?,?,?,?) 
ON DUPLICATE KEY UPDATE visit_count=visit_count+1,ip=?,visit_time=NOW()
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:oracle游标循环和时间函数实例Next article:全文检索