merge 分表

一、先创建 N个表如:client_0,clien_1...clien_N

$c=0;
$sql='';
while ($c<40) {

        $sql="CREATE TABLE `sd_client_".$c."` (
                `id` int(16) unsigned NOT NULL AUTO_INCREMENT,
                `name` varchar(32) DEFAULT NULL COMMENT '客户名称',
             
                PRIMARY KEY (`id`),
          
        ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;";
        echo $sql;
        echo '<br/>';
        $c++;
}

  

二、创建mrg 总表

 $j=0;

$tab_str='';
while($j<40){
    $tab_str.=$j==0?"sd_client_{$j}":','."sd_client_{$j}";
    $j++;
}

$sql="CREATE TABLE IF NOT EXISTS `sd_client` (   
        `id` int(16) unsigned NOT NULL AUTO_INCREMENT,
       `name` varchar(32) DEFAULT NULL COMMENT '客户名称',

    ) ENGINE=MRG_MyISAM INSERT_METHOD=LAST AUTO_INCREMENT=1 UNION=(".$tab_str.")";

echo $sql;
        

三、插入数据

1、hash获取表名

   //id作为主键,对id做hash
    public function get_hash_table($table,$code,$s=40){
          $hash = sprintf("%u", crc32($code));
          $hash1 = intval(fmod($hash, $s));
          return $table.$hash1;
    }
    //统计条数
    public function get_data_count(){
        //$sql="SELECT count(*) FROM sd_client";
        try{
            $count=M('client')->count();
            return  intval($count);
        }catch(PDOException $E){
            //return $E->getMessage();
            return ['code'=>-1,'msg'=>'get_data_count异常'.$E->getMessage()];
        }
        
    }

2、表操作

   $count=get_data_count();
   $table_name=get_hash_table('client_',$count);
   $id=M( $table_name)->add($data);

  

posted @ 2019-05-25 18:29  AlienChan  阅读(149)  评论(0)    收藏  举报