当前位置:   article > 正文

mysql进阶&复制表语句insert into table() select () from table_insert into table select from

insert into table select from

一、insert into…select …PK select into from…

-- 注意mysql不支持该语法
select * into target_table from source_table;
-- mysql中可使用下面代替select ... into 
Create table Table2 (Select * from f6dos.1);
Create table Table3 (Select q from f6dos.1);

-- 常用这个语句
insert into target_table(column1,column2) select column1,5 from source_table; 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

以上两句都是将源表source_table的记录插入到目标表target_table,但两句又有区别。
第一句(select into from)要求目标表target_table不存在,因为在插入时会自动创建。mysql暂时不支持该语法
第二句(insert into select from)要求目标表target_table存在,由于目标表已经存在,所以我们除了插入源表source_table的字段外,还可以插入常量,

二、insert into…select造成锁表

当迁移的表数据量比较多大的时候危险。
insert into … select容易造成死锁的原因,后面的select语句对后表会逐步加s锁,前面的insert数量不一定,导致锁住另一个表整表auto-inc锁。 锁越多越容易出现死锁问题。

三、表归档

-- 复制表结构,新建临时表
create table gb_user_sel_history_tmp like gb_user_sel_history ;
-- 复制数据
insert into table1 
select * from table2 where create_date >'2019-09-15';
-- 快速切换表
rename table table1 to table2;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

注意: select 后面的表语句可以是复合语句,包括各种连表操作。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/410204
推荐阅读
相关标签
  

闽ICP备14008679号