简体   繁体   English

PHP/MySQL 按列分组结果

[英]PHP/MySQL group results by column

in order to keep as few SQL statements as possible, I want to do select set from MySQL:为了保持尽可能少的 SQL 语句,我想从 MySQL 中选择集:

SELECT * FROM products WHERE category IN (10,120,150,500) ORDER BY category,id;

Now, I have list of products in following manner:现在,我有以下方式的产品列表:

CATEGORY
 - product 1
 - product 2
CATEGORY 2
 - product 37
...

What's the best and most efficent way to process MySQL result?处理 MySQL 结果的最佳和最有效的方法是什么?

I thought something like (pseudo PHP)我想像(伪 PHP)

foreach ($product = fetch__assoc($result)){
  $products[$category][] = $product;
}

and then when outputting it, do foreach loop:然后在输出时,执行 foreach 循环:

foreach($categories as $category){
  foreach($products[$category] as $product){
    $output;
  }
}

Is this the best, or is something magical like mysql_use_groupby or something?这是最好的,还是像mysql_use_groupby神奇东西?

Like mluebke commented, using GROUP means that you only get one result for each category.就像mluebke评论的那样,使用 GROUP 意味着您只能为每个类别获得一个结果。 Based on the list you gave as an example, I think you want something like this:根据您提供的列表作为示例,我认为您想要这样的东西:

$sql = "SELECT * FROM products WHERE category IN (10,120,150,500) GROUP BY category ORDER BY category, id";
$res = mysql_query($sql);

$list = array();
while ($r = mysql_fetch_object($res)) {
  $list[$r->category][$r->id]['name'] = $r->name;
  $list[$r->category][$r->id]['whatever'] = $r->whatever;
  // etc
}

And then loop through the array.然后遍历数组。 Example:例子:

foreach ($list as $category => $products) {
  echo '<h1>' . $category . '</h1>';

  foreach ($products as $productId => $productInfo) {
    echo 'Product ' . $productId . ': ' . $productInfo['name'];
    // etc
  }

}

Nope, I think your solution is the best for this problem.不,我认为您的解决方案是解决此问题的最佳方法。 It seems that what's important for you is the output later on, so you should stick with your approach.似乎对您来说重要的是稍后的输出,因此您应该坚持使用您的方法。

Do you want to get a list of categories or actually get all products grouped into categories?您是要获取类别列表还是实际将所有产品分组到类别中?

If it's the latter, best to do:如果是后者,最好这样做:

SELECT 
p.product_id, 
p.name, 
p.category_id, 
c.name AS category 
FROM products p 
JOIN categories c ON (c.category_id = p.category_id AND p.category_id IN (x,y,z))

Then in PHP you can go through the array (psuedo code):然后在 PHP 中你可以遍历数组(伪代码):

    $cats = array();

    foreach($products as $product) { 
        if(!in_array($product['category'], $cats)) {
            $cats[$product['category_id']] = $product['category'];
        }
        $cats[$product['category_id']][$product['product_id']] = $product['name'];
    }

Which will leave you with $cats as an array with products sorted into it.这将使您将 $cats 作为一个数组,并将产品分类到其中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM