在日常工作中,我们经常要把一个数据库实例的表结构和部分数据挪到另外一个数据库实例。如果我们只把表结构复制过去,然后再初始化数据,可能工作量会比较大。
我们通常的做法是,先把一个数据库实例的表结构和所有数据都复制到另外一个数据库实例,然后再去做删除数据和更新数据库,这样,工作量会相对较少,可以省下一些时间。
那么,怎么批量更新或删除多个表的部分数据呢?
1、编写sql脚本
先写好一个sql脚本保存下来,以后要用的话拿出来略作修改就可以用了。
拼装删除的sql脚本:
select
CONCAT(
'delete from ',
table_name,
' where org_id != \'O01\';'
) as delete_sql
from
information_schema.tables
Where table_schema = 'webos' ;
还可以带上条件,比如只想删除某种前缀的表:
select
CONCAT(
'delete from ',
table_name,
' where org_id != \'O01\';'
) as delete_sql
from
information_schema.tables
Where table_schema = 'webos'
and table_name like 'sys_%';
拼装更新的sql脚本:
select
CONCAT(
'update ',
table_name,
' set org_id = \'O02\''
' where org_id != \'O01\';'
) as update_sql
from
information_schema.tables
Where table_schema = 'webos';
带上条件的:
select
CONCAT(
'update ',
table_name,
' set org_id = \'O02\''
' where org_id != \'O01\';'
) as update_sql
from
information_schema.tables
Where table_schema = 'webos'
and table_name like 'sys_%';
2、执行sql脚本
我们可以直接在数据库可视化管理工具上执行,比如navicat,这里我们的操作就以navicat为例。
执行拼装删除语句:
选中查询结果,把语句复制出来:
然后执行复制出来的语句:
这样,就达到了批量部分删除数据的效果了。
批量更新,也是一个道理。
执行拼装更新语句:
选中查询结果,把语句复制出来:
然后执行复制出来的语句:
这样,也完成了批量更新部分数据。
其实,不止以上两种场景,批量修改表字段类型、批量新增字段、批量删除字段,等等,我们都可以用这种方法来做。
比如,批量修改表字段类型:
select
CONCAT(
'alter table ',
table_name,
' modify column remark varchar(255);'
) as modify_sql
from
information_schema.tables
Where table_schema = 'webos'
and table_name like 'sys_%';
根据你的需求,其实可以用information_schema.tables这个表做很多事情。