zoukankan      html  css  js  c++  java
  • 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);
    ?>
  • 相关阅读:
    计算机图形学
    2017.3.20
    史上最强型人养成秘籍: 90 天肥仔变型男实录
    Word 2013发布博客测试
    eeeeeeeeeee
    测试,使用word2013发布博客园博客
    Win7系统桌面便签怎么添加?
    开启两步验证的教程
    【Todo】 cygwin下emacs中M-x shell 中出现乱码
    emacs的LoadPath
  • 原文地址:https://www.cnblogs.com/6min/p/11122919.html
Copyright © 2011-2022 走看看