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);
?>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM