日期:2014-05-16 浏览次数:20815 次
一般来说,当我们的数据库的数据超过了100w记录的时候就应该考虑分表或者分区了,这次我来详细说说分表的一些方法。目前我所知道的方法都是MYISAM的,INNODB如何做分表并且保留事务和外键,我还不是很了解。
首
先,我们需要想好到底分多少个表,前提当然是满足应用。这里我使用了一个比较简单的分表方法,就是根据自增id的尾数来分,也就是说分0-9一共10个
表,其取值也很好做,就是对10进行取模。另外,还可以根据某一字段的md5值取其中几位进行分表,这样的话,可以分的表就很多了。
好了,先来创建表吧,代码如下
CREATE TABLE `test`.`article_0` ( `id` BIGINT( 20 ) NOT NULL , `subject` VARCHAR( 200 ) NOT NULL , `content` TEXT NOT NULL , PRIMARY KEY ( `id` ) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci CREATE TABLE `test`.`article_1` ( `id` BIGINT( 20 ) NOT NULL , `subject` VARCHAR( 200 ) NOT NULL , `content` TEXT NOT NULL , PRIMARY KEY ( `id` ) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci CREATE TABLE `test`.`article_2` ( `id` BIGINT( 20 ) NOT NULL , `subject` VARCHAR( 200 ) NOT NULL , `content` TEXT NOT NULL , PRIMARY KEY ( `id` ) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci CREATE TABLE `test`.`article_3` ( `id` BIGINT( 20 ) NOT NULL , `subject` VARCHAR( 200 ) NOT NULL , `content` TEXT NOT NULL , PRIMARY KEY ( `id` ) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci CREATE TABLE `test`.`article_4` ( `id` BIGINT( 20 ) NOT NULL , `subject` VARCHAR( 200 ) NOT NULL , `content` TEXT NOT NULL , PRIMARY KEY ( `id` ) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci CREATE TABLE `test`.`article_5` ( `id` BIGINT( 20 ) NOT NULL , `subject` VARCHAR( 200 ) NOT NULL , `content` TEXT NOT NULL , PRIMARY KEY ( `id` ) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci CREATE TABLE `test`.`article_6` ( `id` BIGINT( 20 ) NOT NULL , `subject` VARCHAR( 200 ) NOT NULL , `content` TEXT NOT NULL , PRIMARY KEY ( `id` ) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci CREATE TABLE `test`.`article_7` ( `id` BIGINT( 20 ) NOT NULL , `subject` VARCHAR( 200 ) NOT NULL , `content` TEXT NOT NULL , PRIMARY KEY ( `id` ) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci CREATE TABLE `test`.`article_8` ( `id` BIGINT( 20 ) NOT NULL , `subject` VARCHAR( 200 ) NOT NULL , `content` TEXT NOT NULL , PRIMARY KEY ( `id` ) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci CREATE TABLE `test`.`article_9` ( `id` BIGINT( 20 ) NOT NULL , `subject` VARCHAR( 200 ) NOT NULL , `content` TEXT NOT NULL , PRIMARY KEY ( `id` ) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci
?好了10个表创建完毕了,需要注意的是,这里的id不能设为自增,而且所有的表结构必须一致,包括结构,类型,长度,字段的顺序都必须一致 那么对于这个id如何取得呢?后面我会详细说明。现在,我们需要一个合并表,用于查询,创建合并表的代码如下
CREATE TABLE `tes