Adam
Adam

Reputation: 307

Left Join only returning one row

I am trying to join two tables. I would like all the columns from the product_category table (there are a total of 6 now) and count the number of products, CatCount, that are in each category from the products_has_product_category table. My query result is 1 row with the first category and a total count of 68, when I am looking for 6 rows with each individual category's count.

<?php
          $result = mysql_query("
                        SELECT a.*, COUNT(b.category_id) AS CatCount
                        FROM `product_category` a
                        LEFT JOIN `products_has_product_category` b
                        ON a.product_category_id = b.category_id
                    ");
          while($row = mysql_fetch_array($result)) {

              echo '
              <li  class="ui-shadow" data-count-theme="d">
              <a href="' . $row['product_category_ref_page'] . '.php" data-icon="arrow-r" data-iconpos="right">' . $row['product_category_name'] . '</a><span class="ui-li-count">' . $row['CatCount'] . '</span></li>';
          }

        ?>

I have been working on this for a couple of hours and would really appreciate any help on what I am doing wrong.

Upvotes: 3

Views: 2764

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270647

In absence of a GROUP BY clause, the COUNT() aggregate can only return one row, holding the total count for the table after filtering by the WHERE clause. I suspect you mean to GROUP BY b.category_id in a LEFT JOIN against a subquery:

SELECT
  a.*,
  catcount
FROM
  product_category a
  LEFT JOIN (
    SELECT category_id, COUNT(*)  AS catcount
    FROM products_as_product_category 
    GROUP BY category_id
  ) subcount ON a.product_category_id = subcount.category_id

It is because MySQL is lenient about the contents and presence of the GROUP BY clause that your query was syntactically successful in the first place. It would have failed in most other RDBMS because of a missing GROUP BY. Depending on the contents of your table product_category, MySQL may permit you to do the above without the joined subquery, and instead include the correct columns from product_category in the GROUP BY clause, but without knowing the contents of that table I can't say for sure, and the above method is standard and portable across other RDBMS without relying on MySQL's lenience.

A final note, although I have done it above, I never recommend doing SELECT * in a JOIN query. Common column names between the joined tables require aliases to differentiate in the PHP API, introducing confusion. Always best to be explicit about the columns you actually need in the SELECT list.

Upvotes: 4

Related Questions