php - How to order the category that has most product -
i'm not clear in 1 of mysql. have 2 tables:
tblcategory
id, name
tblproduct
id, name, qty, price, category_id
and when use sql select catogories order product count:
select c.id,c.name,count(p.id) product_count tblcategory c inner join tblproduct p on c.id=p.category_id group c.id,c.name order product_count;
the result category has no product not appear in result! how can of them?
you need use left outer join
:
select c.id,c.name,count(p.id) product_count tblcategory c left outer join tblproduct p on c.id=p.category_id group c.id,c.name order product_count;
the inner join
keeps records match in both tables. want product categories, when there no matches. left outer join
keeps records in first table (tblcategory
) along matching records in second table (tblproduct
). if there no products on category, you'll value of 0 instead of missing row.
Comments
Post a Comment