barkster Posted April 9, 2006 Share Posted April 9, 2006 I'm trying to list my categories and how many items are in each category. I'm not much on sub queries. How can I combine these two items. I'd like to display the category and the corresponding number of items in eachCats:SelectCategory.CategoryID,Category.Category,Category.SortingFromCategoryOrder ByCategory.Sorting DescItems:Select Count(Listings.CategoryID)FromListingsGroup ByListings.CategoryID Quote Link to comment https://forums.phpfreaks.com/topic/6923-count-items-in-each-category/ Share on other sites More sharing options...
fenway Posted April 9, 2006 Share Posted April 9, 2006 This should work (UNTESTED):[code]SelectCategory.CategoryID,Category.Category,Category.Sorting,(Select Count(CategoryID)FromListings WHERE CategoryID = Category.CategoryID) AS cntFromCategoryOrder ByCategory.Sorting Desc[/code] Quote Link to comment https://forums.phpfreaks.com/topic/6923-count-items-in-each-category/#findComment-25293 Share on other sites More sharing options...
barkster Posted April 10, 2006 Author Share Posted April 10, 2006 Thanks for the help, I messed with it for a while and can't get it to work. i tried the followingSelectCategory.CategoryID,Category.Category,Category.Sorting,(Select Count(Listings.CategoryID)FromListings WHERE Listings.CategoryID = Category.CategoryID) AS cntFromCategoryOrder ByCategory.Sorting Desc& SelectCategory.CategoryID,Category.Category,Category.Sorting,(Select Count(Listings.CategoryID) as cntFromListings WHERE Listings.CategoryID = Category.CategoryID)FromCategoryOrder ByCategory.Sorting Desc Quote Link to comment https://forums.phpfreaks.com/topic/6923-count-items-in-each-category/#findComment-25381 Share on other sites More sharing options...
fenway Posted April 10, 2006 Share Posted April 10, 2006 There's nothing wrong with the query I provided, but it does require MySQL 4.1+ for subselects to work. Quote Link to comment https://forums.phpfreaks.com/topic/6923-count-items-in-each-category/#findComment-25513 Share on other sites More sharing options...
barkster Posted April 10, 2006 Author Share Posted April 10, 2006 Ah, 4.0.25 glad you mentioned it, just moved to a new host and was supposed to have 4.1. Now I know why I couldn't get any sub selects to work. I did though get it to work like thisSelect Category.CategoryID, Category.Category, Category.Sorting, Count(Listings.CategoryID) as cntFrom Category LEFT JOIN Listings on(Listings.CategoryID=Category.CategoryID)Group ByCategory.CategoryIDOrder ByCategory.Sorting AscThanks for the help. Quote Link to comment https://forums.phpfreaks.com/topic/6923-count-items-in-each-category/#findComment-25533 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.