0

我有下一个mysql查询:

    $productn = $jdb->query('SELECT t2.title FROM '.DB_PREFIX.'shopping_cart AS t1 LEFT JOIN '.DB_PREFIX.'shop_order_details AS t2 ON t1.shopid WHERE t1.session = "'.smartsql($_SESSION['shopping_cart']).'"');

while ($rowp = $productn->fetch_assoc()) {
// my product title
 $productname = $rowp["title"];
}

使用 print_r($productname); 我得到类似的东西:

姓名1姓名1姓名1姓名2姓名2

我想显示类似:

3 x 名称1 2 x 名称2

或者

3 x 名称 1、2 x 名称 2

有可能做到这一点吗?

4

5 回答 5

5

SQL 查询将是这样的:

select name,count(name) from table group by name ;

希望这对您有所帮助。

于 2012-06-18T18:20:56.803 回答
1

您可能希望按标题分组并计算每个分组的出现次数。

SELECT t2.title, COUNT(t2.title)
FROM shopping_cart AS t1
LEFT JOIN shop_order_details AS t2 ON t1.shopid
WHERE t1.session = <session>
GROUP BY t2.title

看一下COUNT(*)andGROUP BY函数参考。

于 2012-06-18T18:22:19.200 回答
1

您可以使用 group by close 和 count(*) group 函数,如下所示

$productn = $jdb->query('SELECT t2.title, count(t2.title) num FROM '.DB_PREFIX.'shopping_cart AS t1 LEFT JOIN '.DB_PREFIX.'shop_order_details AS t2 ON t1.shopid WHERE t1.session = "'.smartsql($_SESSION['shopping_cart']).'" group by t2.title');

while ($rowp = $productn->fetch_assoc()) {
// my product title
 $productname = $rowp["title"];
 $numberofproducts  = $rowp["num"];
}

这应该工作......

于 2012-06-18T18:22:21.677 回答
1

好的,我终于能够做出我想要的,所以我想在这里分享它以备将来使用。

这就是我所做的:

$productn = $jdb->query('SELECT t2.title, count(t2.title) num FROM '.DB_PREFIX.'shop_order_details AS t2 WHERE t2.orderid ="'.$orderid.'" GROUP BY t2.title');

while($registro=$productn->fetch_array()){
 echo $registro['title'].' x '.$registro['num']."<br>";
}

我在课堂上定义了 fetch_array() :

    function fetch_assoc() {
    if($this->result) {
        return mysql_fetch_assoc($this->result);
    } else {
        return false;
    }
}

谢谢大家的帮助。我给大家加分了!

于 2012-06-19T09:39:42.510 回答
1

If you want to do it with PHP, use:

$total_products = array();
while ($rowp = $productn->fetch_assoc()) {
   $productname = $rowp['title'];
   if(isset($total_products[$productname])) {
      ++$total_products[$productname];
   }
   else
   {
      $total_products[$productname] = 1;
   }
}

UPD 1: Show products in desired format:

foreach($total_products as $name => $num) {
   echo "{$num} x {$name}, ";
}
于 2012-06-18T18:26:51.097 回答