mysql-merge合並表 [sql] 注意: 1 每個子表的結構必須一致,主表和子表的結構需要一致, 2 每個子表的索引在merge表中都會存在,所以在merge表中不能根據該索引進行唯一性檢索。 3 子表需要是MyISAM引擎 4 AUTO_INCREMENT 不會按照你所期望的方式工作。 建表語句
create table tablename(正常的字段)engine=merge insert_method=last
insert_method: 有兩個值如下: LAST 如果你執行insert 指令來操作merge表時,插入操作會把數據添加到最後一個子表中。 FIRST 同理,執行插入數據時會把數據添加到第一個子表中。 例子:
create table user1( id int(10) not null auto_increment, name varchar(50), sex int(1), primary key(id) )engine=myisam charset=utf8; create table user2( id int(10) not null auto_increment, name varchar(50), sex int(10) ,primary key(id) )engine=myisam charset=utf8; insert into user1 (name,sex) values('張三',0); insert into user2 (name,sex) values('lisi',1); mysql> select * from user1; +----+------+------+ | id | name | sex | +----+------+------+ | 1 | 張三 | 0 | +----+------+------+ mysql> select * from user2; +----+------+------+ | id | name | sex | +----+------+------+ | 1 | lisi | 1 | +----+------+------+ create table alluser( id int(10) not null auto_increment, name varchar(50), sex int(10), index(id) )type=merge union=(user1,user2) insert_method=last; mysql> select * from alluser; +----+------+------+ | id | name | sex | +----+------+------+ | 1 | 張三 | 0 | | 1 | lisi | 1 | +----+------+------+ mysql> insert into alluser(name,sex) values('嘿嘿',0); mysql> select * from user1; +----+------+------+ | id | name | sex | +----+------+------+ | 1 | 張三 | 0 | +----+------+------+ 1 row in set (0.00 sec) mysql> select * from user2; +----+------+------+ | id | name | sex | +----+------+------+ | 1 | lisi | 1 | | 2 | 嘿嘿 | 0 | +----+------+------+
2 rows in set (0.00 sec) //他把這條數據存入了user2表裡是因為我們的insert_method的參數填寫的是last
mysql> update alluser set sex=replace(sex,0,1) where id=2; +----+------+------+ | id | name | sex | +----+------+------+ | 1 | 張三 | 0 | | 1 | lisi | 1 | | 2 | 嘿嘿 | 1 | +----+------+------+