---
title: "mysql主键记录存在更新某字段"
author: "awfrun"
date: "2015-01-07T15:08:26Z"
tags: []
categories: ["数据库"]
slug: "mysql"
draft: false
lastmod: "2015-01-07T15:08:26Z"
id: 2173585
url: "https://awfrun.iteye.com/blog/2173585"
---

1.以一个表的数据为基准向另外的表中插入数据，如果主键记录存在更新某字段

insert into role(player\_id,hp,mp) select player\_id,0,0 from player on duplicate key update hp=3; 

\*update hp=3 表示如果是主键存在的情况下执行

INSERT INTO t\_player(player\_id,carrier\_operator) SELECT a.player\_id,b.pt from t\_player a JOIN t\_z\_temp b ON (a.login\_name = b.\`name\` OR a.guest\_key = b.phone\_id)  on DUPLICATE key UPDATE carrier\_operator=b.pt; 

 

2.找出不存在的记录插入到表中

insert into role(player\_id,hp,mp) select player\_id,0,0 from player WHERE not exists (SELECT * from role where role.player\_id=player.player\_id);