首页 > 代码库 > mysql用merge合并表

mysql用merge合并表

merge合并表的要求

1.合并的表使用的必须是MyISAM引擎

2.表的结构必须一致,包括索引、字段类型、引擎和字符集

实例:

create table if not exists user1(

  id int(11) not null auto_increment,

  name varchar(50) default null,

  sex int(1) not null default 0,

  primary key (id)

)engine = MyISAM default charset = utf8 auto_increment=1;

 

create table if not exists user2(

  id int(11) not null auto_increment,

  name varchar(50) default null,

  sex int(1) not null default 0,

  primary key (id)

)engine = MyISAM default charset = utf8 auto_increment=1;

 

create table if not exists alluser(

  id int(11) not null auto_increment,

  name varchar(50) default null,

  sex int(1) not null default 0,

  primary key (id)

)engine = merge union=(user1,user2) insert_method = last auto_increment=1;

执行insert into alluser (name,sex) values (‘tian‘,1);报错如下:

ERROR 1168 (HY000): Unable to open underlying table which is differently defined or of non-MyISAM type or doesn‘t exist

百度了一下原来是默认字符集没写,修改如下

create table if not exists alluser1(

  id int(11) not null auto_increment,

  name varchar(50) default null,

  sex int(1) not null default 0,

  primary key (id)

)engine = merge union=(user3,user4) insert_method = last auto_increment=1 default charset=utf8;

执行insert into alluser1 (name,sex) values (‘tian‘,1);成功

执行select * from alluser1;显示如下:

+----+------+-----+
| id | name | sex |
+----+------+-----+
| 1 | tian | 1 |
+----+------+-----+

执行select * from user2;显示如下:

+----+------+-----+
| id | name | sex |
+----+------+-----+
| 1 | tian | 1 |
+----+------+-----+

mysql用merge合并表