SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot
    Join Date
    Mar 2004
    Location
    New Jersey
    Posts
    140
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    fetch categories/number of items where number of items = 0

    Hey,
    I'm crafting a SQL query that should return the category names as number of items in the categories (listings.* where listings.category = categories.id). The query works fine when there are items, but when there are 0 items in the category, the category isn't returned.

    Code:
    select categories.name as name
         , count(listings.id) as count
      from categories
         , listings
     where listings.category = categories.id
     group
        by categories.name
    Any help?

  2. #2
    SitePoint Wizard bronze trophy JRMillion's Avatar
    Join Date
    Apr 2004
    Location
    Arlington VA
    Posts
    2,094
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    well the join with listings will prevent categories with no listings from being returned...
    you may need to do multiple or sub-queries.

    you could have a "null" listing for each category and just ignore it.... but that doesnt seem like a great solution....

  3. #3
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,269
    Mentioned
    60 Post(s)
    Tagged
    3 Thread(s)
    james, allow me to introduce you to the concept of outer joins
    Code:
    select categories.name    as name
         , count(listings.id) as thecount
      from categories
    left outer
      join listings
        on categories.id
         = listings.category  
    group
        by categories.name
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •