简体   繁体   中英

PHP MySQL DISTINCT/GROUP BY

I have the following tables:


- Table 'Category_sub' -

  • Subcategory_id
  • Subcategory_maincatid
  • Subcategory_name

- Table 'Products_categories' -

  • Products_categories_product_id
  • Products_categories_category_id

- Table 'Products' -

  • Products_id
  • Products_itemnumber
  • Products_subitemnumber

I want to show the names of the categories and the number of products in this categorie.

Each product has an item number (not unique) and a subitem number (unique). subitem numbers will be used for different colors/types of the same product.

I have the following script:

<?php

$sql= $db->prepare("
    SELECT *,
    COUNT(DISTINCT Products_itemnumber) AS Products_total
    FROM
        Category_sub,
        Products_category,
        Products
    WHERE
        Subcategory_maincatid=:cat_id
        AND Subcategory_id=Products_categories_category_id
        AND Products_categories_product_id_id=Products_id
    GROUP BY Subcategory_name
");

$sql->bindValue(':cat_id', $_GET['cat_id'], PDO::PARAM_INT);
$sql->execute();
$sql_fetch= $sql->fetchAll(PDO::FETCH_ASSOC);

foreach($sql_fetch as $category) {
    echo $category['Subcategory_name'] ."(". $category['Products_total'] .")<br />";
}

?>

The script above is not working properly. I have two products with the same itemnumber, the script should count it as one product. The script above is counting two products.

select Subcategory_name, COUNT(*)
from Category_sub 
      JOIN Products_categories ON Products_categories_category_id = Subcategory_id
      JOIN Products ON Products_id = Products_categories_product_id
group by Subcategory_name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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