mysql - php可以按天連續去兩周的更新資料嗎

來源:互聯網
上載者:User
use_id reg_time1      2015-12-01 2      2015-12-02 3      2015-12-02 4      2015-12-03 5      2015-12-03 6      2015-12-03 7      2015-11-30   

要得到
`

reg_time    count count(2周內)2015-12-01   0    02015-11-29   0    02015-11-30   1    12015-11-31   0    12015-12-01   1    22015-12-02   2    42015-12-03   3    7

`

目的就是取出當天註冊 以及當天往前推14天的註冊數量

現在的做法是迴圈count
`

$lasttime=strtotime(date("Y-m-d",time()))-14*3600*24;$firsttime=strtotime(date("Y-m-d",time()))+3600*24;$result = array()for($i=13;$i>=0;$i--){    $first=date("Y-m-d",$firsttime-$i*3600*24);    $last=date("Y-m-d",$lasttime-$i*3600*24);    $today=date("Y-m-d",time()-$i*24*3600);    $tmp1 = "select count(1) from table where reg_time > $last and reg_time < $last";    $tmp2 = "select count(1) from table where reg_time = $today "    $result[][date] =$today;    $result[][count1] =$tmp1;    $result[][count2] =$tmp2;        }

`

這樣做的結果就是一共執行了28次count 感覺效率相當低下 求最佳化思路

回複內容:

use_id reg_time1      2015-12-01 2      2015-12-02 3      2015-12-02 4      2015-12-03 5      2015-12-03 6      2015-12-03 7      2015-11-30   

要得到
`

reg_time    count count(2周內)2015-12-01   0    02015-11-29   0    02015-11-30   1    12015-11-31   0    12015-12-01   1    22015-12-02   2    42015-12-03   3    7

`

目的就是取出當天註冊 以及當天往前推14天的註冊數量

現在的做法是迴圈count
`

$lasttime=strtotime(date("Y-m-d",time()))-14*3600*24;$firsttime=strtotime(date("Y-m-d",time()))+3600*24;$result = array()for($i=13;$i>=0;$i--){    $first=date("Y-m-d",$firsttime-$i*3600*24);    $last=date("Y-m-d",$lasttime-$i*3600*24);    $today=date("Y-m-d",time()-$i*24*3600);    $tmp1 = "select count(1) from table where reg_time > $last and reg_time < $last";    $tmp2 = "select count(1) from table where reg_time = $today "    $result[][date] =$today;    $result[][count1] =$tmp1;    $result[][count2] =$tmp2;        }

`

這樣做的結果就是一共執行了28次count 感覺效率相當低下 求最佳化思路

select reg_time,count(1) from table where reg_time > $last and reg_time < $last group by reg_time

用sql分組查詢

針對你的問題,建議你直接擷取每天的更新資料,在PHP自己加一下。這樣SQL能減少到只剩一個。

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.