最近在做项目的时候需要插入数据的时候先查询表中是否有数据,有的话更新数据,没有的话插入数据。
可以用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)
老做法是写三条sql语句:
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操作
这种写法比较麻烦
用on duplicate key update 的做法如下:
insert into player_count(player_id,count) value(1,1) on duplicate key update count=count 1;
这样每次不管插入还是更新都调用这句语句就能达到我们要的效果,省了不少的判断。
你打算打赏多少钱呢?

(微信扫一扫)