Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Join, group by, for listing categories with products quantities

Status
Not open for further replies.

hmoner

Programmer
Mar 3, 2005
7
Hi guys
I'm not having a nice time trying to make this query work
I have 2 tables
category
product

I want to list the following way
CATEGORY.NAME | CATEGORY.DESC | PRODUCT_COUNT

The following query works, but it doesn't list the categories that doesn't have products added. I'd like (if possible) to show "0" in PRODUCT_COUNT column, when the category doesn't have products added.

; ==========
SELECT category.id, COUNT(product.fk_category) AS product_count, category.name, category.description FROM product, category WHERE category.id = product.fk_category
GROUP BY product.fk_category
ORDER BY category.name ASC
; ==========

Thanks a lot in advance...
 
what you need is a LEFT OUTER JOIN

change your query to --

SELECT category.id, COUNT(product.fk_category) AS product_count, category.name, category.description
[red]FROM category LEFT OUTER JOIN product
ON[/red] category.id = product.fk_category
GROUP BY [red]category.id[/red]
ORDER BY category.name ASC


you're using MySQL, right? ;-)



r937.com | rudy.ca
 
Hi r937
Yes, I'm using mySQL

I've tried the following and worked:

SELECT category.id, COUNT(product.fk_category) AS product_count, category.name, category.description FROM product RIGHT JOIN category ON category.id = product.fk_category
GROUP BY category.id
ORDER BY category.name ASC

Which one should I use? LEFT OUTER JOIN or RIGHT JOIN ? and why ?

Thanks a lot again
 
you should use whichever makes sense for you

most people think from left to right

perhaps you more comfortable to left from right thinking are

:)

note that

category LEFT OUTER JOIN product

is exactly the same as

product RIGHT OUTER JOIN category



r937.com | rudy.ca
 
Anyway the GROUP BY clause is incomplete in ANSI SQL:
Code:
SELECT category.id, COUNT(product.fk_category) AS product_count, category.name, category.description
FROM product RIGHT JOIN category ON category.id = product.fk_category
GROUP BY category.id[!], category.name, category.description[/!]
ORDER BY category.name ASC

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top