使用MySql replace into(insert into 的增强版)时你不得不注意的坑

来源:互联网 发布:php reflection的作用 编辑:程序博客网 时间:2024/06/05 04:34

使用MySql replace into(insert into 的增强版)时你不得不注意的坑

使用之前,你必须先搞懂它的原理,本文从以下几个方面介绍:replace into的应用场景;replace into的原理;replace into的应用注意事项,replace into的应用形式


 (1) MySQL replace into 是insert into 的增强版本,它主要用于以下场景:

在向表中插入数据的时候,经常遇到这样的情况:1. 首先判断数据是否存在; 2. 如果不存在,则插入;3.如果存在,则更新。

在 SQL Server 中可以这样处理:


   if not exists (select 1 from t where id = 1)      insert into t(id, update_time) values(1, getdate())   else      update t set update_time = getdate() where id = 1

那么 mysql 中如何实现这样的逻辑呢?别着急 mysql中有更简单的方法: replace into

replace into t(id, update_time) values(1, now());

replace into t(id, update_time) select 1, now();

(2)replace into原理


replace into 跟 insert 功能类似,不同点在于:replace into 首先尝试插入数据到表中,

 如果发现表中已经有此行数据(根据主键或者唯一索引判断)则先删除此行数据,然后插入新的数据。 2. 否则没有此行数据的话,直接插入新数据。


(3)replace into的应用注意事项


1)插入数据的表必须有主键或者是唯一索引!否则的话,replace into 会直接插入数据,这将导致表中出现重复的数据。

2)如果数据库里边有这条记录,则直接修改这条记录;如果没有则,则直接插入,在有外键的情况下,对主表进行这样操作时,因为如果主表存在一条记录,被从表所用时,直接使用replace into是会报错的,这和replace into的内部原理是相关(ps.它会先删除然后再插入)。

3)正确做法是- 即先删除该条存在的数据,然后再次插入这条数据,这和外键约束相悖呢,因此只能采用update和insert这样的组合,来应对外键约束

          sql_select_1='''select * from one_and_two_stars where kn_id = %d ''' %( int(one_level_id))
            res_num_1= self.execute_kg(sql_select_1)
            if res_num_1 > 0:
                # 修改该条记录
                sql_update_one_and_two_stars='''update 
one_and_two_stars set  kn_name = %s, parent_kn_id = %s where kn_id = %s'''  ("'"+str(kn_name_1)+"'", str(parent_kn_id_1), int(one_level_id))

                self.execute_kg(sql_update_one_and_two_stars)
                self.commit_kg()
            else:
                # 直接插入这条数据
                sql_insert_one_and_two_stars= '''insert into one_and_two_stars(kn_id,kn_name,parent_kn_id,ctime)
                                                 values('%s','%s','%s','%s') 
                                                 ''' % (str(one_level_id),  str(kn_name_1),str(parent_kn_id_1),str(dt))
               self.execute_kg(sql_insert_one_and_two_stars)
               self.commit_kg()

(4)replace into的使用形式


MySQL replace into 有三种形式:
1) replace into tbl_name(col_name, ...) values(...)2) replace into tbl_name(col_name, ...) select ...3) replace into tbl_name set col_name=value, ...

前两种形式用的多些。其中 “into” 关键字可以省略,不过最好加上 “into”,这样意思更加直观。另外,对于那些没有给予值的列,MySQL 将自动为这些列赋上默认值。


阅读全文
0 0
原创粉丝点击