douqiao2008 2009-11-12 05:17
浏览 12
已采纳

用于组织数据库中的值的代码的效率

I have to put my database's data in this format (values will differ, obviously), I think it's called an associative array (I'm horrible with terminology).

$values=array(
            "Jan" => 110,
            "Feb" => 130,
            "Mar" => 215,
            "Apr" => 81,
            "May" => 310,
            "Jun" => 110,
            "Jul" => 190,
            "Aug" => 175,
            "Sep" => 390,
            "Oct" => 286,
            "Nov" => 150,
            "Dec" => 196
    );

Here's what I developed:

    $sql = "SELECT MONTH(AddDate) AS Date, column_name FROM table ORDER BY AddDate ASC";
    $res = mysql_query($sql) or die(mysql_error());
    $prev_date = null;

$values=array();

while ( $row = mysql_fetch_assoc($res) ) {
    if ( $row['Date'] != $prev_date) {
        $month = $row['Date'];
        $sql = "SELECT count(MONTH(AddDate)) AS EntryAmount FROM `table` WHERE MONTH(AddDate)=$month ";
        $countResults = mysql_query($sql) or die(mysql_error());
        if( $entryAmount = mysql_fetch_array($countResults) ) {
            $values[$row['Date']] =  $entryAmount['EntryAmount'];
        }
        $prev_date = $row['Date'];
    }
}

Output:

Array ( [9] => 999 [10] => 986 [11] => 264 ) 
  • 写回答

2条回答 默认 最新

  • doupeizheng3918 2009-11-12 05:25
    关注

    You can do all of this in a single query:

    select month(AddDate) as theMonth,
           count(*) as numberOfRows
    from   `table`
    group by theMonth
    order by theMonth
    

    Then the outer loop goes away and the inner loop becomes:

    if( $row = mysql_fetch_array($results) ) 
    {
        $values[$row['theMonth']] = $row['numberOfRows'];
    }
    

    It should perform noticeably better for moderately sized data sets. Do note, however, that by using the month function, you lose any benefit of indexes that you might otherwise be able to use.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改