本文實例講述了PHP實現(xiàn)數(shù)據(jù)庫統(tǒng)計時間戳按天分組輸出數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:
比如統(tǒng)計每天用戶注冊數(shù),數(shù)據(jù)庫表存了一張用戶注冊記錄表:
create table table_name(id int primary key,register_time int(10));
register_time記錄的是時間戳,以前的做法是,接收查詢開始時間、查詢結(jié)束時間,然后循環(huán)查詢每天的注冊數(shù)量,代碼:
/* 查詢2015-12-01 至 2015-12-14 */ // 開始的時間戳 $startUnix = 1448899200; // 2015-12-01 00:00:00 // 結(jié)束的時間戳 $endUnix = 1450108800; // 2015-12-15 00:00:00 for($i = $startUnix; $i < $endUnix; $i += 86400){ // 86400為1天的秒數(shù) // 查詢 $sql = 'select count(*) from table_name where register_time>= '.$i.' and register_time < '.$i + 86400; // 執(zhí)行查詢 }
這種方法的弊端就是,查詢開始于結(jié)束的日期相差多少天就查詢檢索數(shù)據(jù)庫多少次。
優(yōu)化方法:
/* 查詢2015-12-01 至 2015-12-14 */ // 開始的時間戳 $startUnix = 1448899200; // 2015-12-01 00:00:00 // 結(jié)束的時間戳 $endUnix = 1450108800; // 2015-12-15 00:00:00 $sql = 'select count(id) as register_count, FROM_UNIXTIME(register_time, '%Y-%m-%d') as datetime from table_name where register_time>= '.$startUnix.' and register_time < '.$endUnix group by datetime; // 執(zhí)行查詢 ...
查詢時把時間戳轉(zhuǎn)成天,最后group by 分組,得到每天的注冊id數(shù),查詢數(shù)據(jù)庫一次
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php+mysql數(shù)據(jù)庫操作入門教程》、《php+mysqli數(shù)據(jù)庫程序設(shè)計技巧總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
【網(wǎng)站聲明】本站除付費源碼經(jīng)過測試外,其他素材未做測試,不保證完整性,網(wǎng)站上部分源碼僅限學(xué)習(xí)交流,請勿用于商業(yè)用途。如損害你的權(quán)益請聯(lián)系客服QQ:2655101040 給予處理,謝謝支持。