Home > Database > Mysql Tutorial > body text

on duplicate key update简单使用

WBOY
Release: 2016-06-07 14:56:46
Original
1153 people have browsed it

1。最近在做项目的时候,遇到这样的一个问题,就是我每做完一件事情,都要更新一下统计表,然而要更新统计表,就要根据主键去统计表里面去查询是否已经有这样的一条记录,如果有那么就更新,如果没有那么就插入一条记录,开始我就是这么干的,结果被老大给否

1。最近在做项目的时候,遇到这样的一个问题,就是我每做完一件事情,都要更新一下统计表,然而要更新统计表,就要根据主键去统计表里面去查询是否已经有这样的一条记录,如果有那么就更新,如果没有那么就插入一条记录,开始我就是这么干的,结果被老大给否决了,他说可以用on duplicate key update去做。下面就实际操作一下吧:
表结构:
+-----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| player_id | int(11) | NO | PRI | NULL | |
| count | int(11) | YES | | NULL | |
+-----------+---------+------+-----+---------+-------+
2 rows in set (0.01 sec)
select * from player_count where player_id = 1;//查询统计表中是否有记录
insert into player_count(player_id,count) value(1,1);//没有记录就执行insert 操作
update player_count set count = count+1 where player_id = 1;//有记录就执行update操作
Copy after login
insert into player_count(player_id,count) value(1,1) on duplicate key update count=count+1;
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!