亿条数据在PHP中实现Mysql数据库分表100张
                        
                            时间:2021-07-01 10:21:17
                            帮助过:3人阅读
							                        
                     
                    
                    
                     $i=
0; 
2 while($i<=
99){ 
3 echo 
"$newNumber \r\n"; 
4 $sql=
"CREATE TABLE `code_".$i.
"` (
 5  `full_code` 
char(
10) NOT NULL, 
6  `create_time` 
int(
10) unsigned NOT NULL, 
7  PRIMARY KEY  (`full_code`), 
8 ) ENGINE=MyISAM DEFAULT CHARSET=utf8
";
 9 mysql_query($sql);
10 $i++; 
下面说一下我的分表规则,full_code作为主键,我们对full_code做hash
函数如下:
1 $table_name=get_hash_table(
‘code‘,$full_code);
2 function get_hash_table($table,$code,$s=
100){
3 $hash = sprintf(
"%u", crc32($code));
4 echo $hash;
5 $hash1 = intval(fmod($hash, $s));
6  return $table.
"_".$hash1;
7 } 
这样插入数据前通过get_hash_table获取数据存放的表名。
最后我们使用merge存储引擎来实现一张完整的code表
1 CREATE TABLE IF NOT EXISTS `code` (  
2 `full_code` 
char(
10) NOT NULL,
3 `create_time` 
int(
10) unsigned NOT NULL,
4 INDEX(full_code)  
5 ) TYPE=MERGE UNION=(code_0,code_1,code_2.......) INSERT_METHOD=LAST ; 
这样我们通过select * 
from code就可以得到所有的full_code数据了。
亿条数据在PHP中实现Mysql数据库分表100张
标签: