php+mysql按月分表, 组合查询

每个月月底最后一天建好下个月的空表 或每年底建1到12月的空表 , table_201901,table_201902,table_201903

增加记录不需要修改,insert到当月对应表就好了。

查询的时候需要代码中判断查询时间范围,union范围内的月份表,组合出查询SQL,  比如查询5月5日到6月5日的数据 ,跨5月和6月表 

组合子查询  (select * from table_201905 UNION ALL select * from table_201906 )

再从子查询结果查询条件下的记录,  不要忘记子查询起个别名    select * from (select * from table_201905 UNION ALL select * from table_201906 ) tmp where dateline between 5月5日 and 6月5日

看代码

<?php
//注册到月份表
$sql = "INSERT INTO tbl_view_".date('Ym')."(ip,city,dateline) VALUES('127.0.0.1','CHINA',1562065253)";
$id  = DB::query($sql);

//查询的时候按时间条件组合查询SQL
$start_date  = strtotime('2019-01-01 00:00:00');
$end_date    = strtotime('2019-07-01 23:59:59');

$month_begin = date('Ym', $start_date);
$month_end   = date('Ym', $end_date);
$month_plus  = 1;
$month_next  = date('Ym', strtotime("+{$month_plus} months", $start_date));
$UNION_SQL   = "SELECT ip,city,dateline FROM tbl_view_{$month_begin}";
while(intval($month_next) <= intval($month_end)){
    $UNION_SQL .= " UNION ALL SELECT ip,city,dateline FROM tbl_view_{$month_next}";
    $month_plus += 1;
    $month_next  = date('Ym', strtotime("+{$month_plus} months", $start_date));
}

$sql = "SELECT * FROM ($UNION_SQL) t WHERE 1 AND dateline BETWEEN $start_date AND $end_date";
$dt  = DB::query($sql);
?>

 

posted @ 2019-07-02 20:18  1553  阅读(4333)  评论(0编辑  收藏  举报