【问题标题】:PHP & MYSQL: using group by for categoriesPHP & MYSQL:使用 group by 分类
【发布时间】:2010-06-04 19:36:44
【问题描述】:

我的数据库有以下设置

productid | productname | category id

我想像这样输出它们:

category #1
item 1 
item 2
item 3

category #2
item 1 
item 2
item 3

我将它们组合在一起使用分组,效果很好,但我想遍历每个组并显示该组的内容。我该怎么做?

【问题讨论】:

  • 发布您正在使用的查询,以便有人可以提供 PHP 来提取数据。
  • 我没有查询,我的问题是使用什么查询。该帖子包括我的数据库设置(包含的数据)以及我希望它如何显示,我还应该包括什么?

标签: php mysql


【解决方案1】:

我建议只使用一个简单的查询来获取所有行,并按类别 ID 排序。仅当其值与上一行发生变化时才输出类别。

<?php

$stmt = $pdo-> query("SELECT * FROM `myTable` ORDER BY categoryID");

$current_cat = null;
while ($row = $stmt->fetch()) {
  if ($row["categoryID"] != $current_cat) {
    $current_cat = $row["categoryID"];
    echo "Category #{$current_cat}\n";
  }
  echo $row["productName"] . "\n";
}

?>

【讨论】:

    【解决方案2】:

    这应该可行:

    $categories = array();
    $result= mysql_query("SELECT category_id, product_name  FROM `table` GROUP BY `catagory_id` ORDER BY `catagory_id`");
    while($row = mysql_fetch_assoc($result)){
        $categories[$row['category_id']][] = $row['product_name'];
    }
    
    // any type of outout you like
    foreach($categories as $key => $category){
        echo $key.'<br/>';
        foreach($category as $item){ 
            echo $item.'<br/>';
        }
    }
    

    您可以自己设置样式的输出。您只需将所有内容添加到一个多维数组中,并将类别 id 作为第一级键。

    编辑:生成的数组可能如下所示:

    $categories = array(
        'cateogy_id_1' => array(
            1 => 'item_1',
            2 => 'item_2',
            ...
        ),
        'cateogy_id_2' => array(
            1 => 'item_1',
            2 => 'item_2',
            ...
        ),
        ....
    );
    

    【讨论】:

      【解决方案3】:

      您想要的是按类别对它们进行排序,而不是对它们进行分组。

      SELECT * FROM MyTable
      ORDER BY category_id, product_id
      

      当你遍历列表时,只要 category_id 发生变化就输出一个新的标题。

      【讨论】:

        【解决方案4】:

        这种方式不需要按照category_id对数据进行排序。

        您可以使用 php 将每个类别组合到一个嵌套数组中。 在此之后,数据可以很容易地显示在表格中,传递到图表/图表库等​​......

        <?php
        $stmt = $pdo-> query("SELECT * FROM myTable ORDER BY categoryID");
        
        
        $categories = []; //the array to hold the restructured data
        
        //here we group the rows from different categories together
        while ($row = $stmt->fetch())
        {
            //i'm sure most of you will see that these two lines can be performed in one step
            $cat = $row["categoryID"]; //category id of current row
            $categories[$cat][] = $row; //push row into correct array
        }
        
        //and here we output the result
        foreach($categories as $current_cat => $catgory_rows)
        {
            echo "Category #{$current_cat}\n";
        
            foreach($catgory_rows as $row)
            {
                echo $row["productName"] . "\n";
            }
        }
        ?>
        

        【讨论】:

          【解决方案5】:

          最简单的方法可能是拉出类别列表,遍历并拉出它们附加的产品。 (即几个查询。)

          例如(伪代码):

          $result = fetch_assoc("SELECT category_id FROM categories");
          foreach($result 作为 $row)
          {
            回声 $row['category_id'];
            $result2 = fetch_assoc("SELECT product_id FROM products");
            foreach($result2 作为 $row2)
            {
              回声 $row2['product_id'];
            }
          }
          

          如果您想在一个查询中完成所有操作,您可以执行以下操作:

          $result = fetch_assoc("SELECT product_id, category_id FROM products p JOIN categories c ON p.category_id = c.category_id ORDER BY c.category_id ASC");
          $最后=空;
          foreach($result 作为 $row)
          {
            # 每当类别发生变化时输出类别
            if($row['category_id'] != 最后一个)
            {
              回声 $row['category_id'];
              $last = $row['category_id'];
            }
            回声 $row['item_id'];
          }

          然后您可以遍历结果集并在类别名称发生变化时提取它。

          可能有一种更复杂、更优雅的方式来编写 SQL 以在从数据库中获取它之前执行所有操作,但我没那么聪明。 ;)

          注意:示例使用伪代码。我使用一个 mysql 抽象类,其工作方式如下:

          $db->query("SELECT stuff");
          $db->multi_result(); // 返回二维关联数组

          然后我可以foreach($db-&gt;multi_result() as $row),超级懒惰,棒极了。

          如果你愿意,我可以发布抽象层的代码。

          【讨论】:

            【解决方案6】:
            $stmt = $dbConnection->prepare("SELECT exam_id, COUNT(report_id) FROM bug_report GROUP BY exam_id; ");
                    //$stmt->bind_param('s',$exam_id); 
                    $stmt->execute();
                    $extract = $stmt->get_result();
                    $count = $extract->num_rows;
                    if($count){
                        while($rows = $extract->fetch_assoc()){
                            $exam_id = $rows["exam_id"];
                            switch($exam_id){
                                case "jee_questions":
                                    $jeeBugCount = $rows["COUNT(report_id)"];
                                    break;
                                case "gate_questions":
                                    $gateBugCount = $rows["COUNT(report_id)"];
                                    break;
                            }
                        }   
                    }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-06-09
              • 2017-10-20
              相关资源
              最近更新 更多