views:

21

answers:

1

Give the query:

SELECT
    tblProducts.ID, tblProducts.views, tblProducts.productName, tblProducts.isForSale, tblProducts.isLimitedStock, tblProducts.stockCount, tblProducts.description, tblProducts.weightKG, tblProducts.basePrice, tblProducts.dateCreated, tblProductCats.catName, 
    (SELECT COUNT(*) FROM tblProductPrices WHERE productId = tblproducts.id) AS priceMods, 
    (SELECT COUNT(*) FROM tblcomments WHERE productId = tblproducts.ID) AS comments,
    (SELECT COUNT(*) FROM tblProductImages WHERE productID = tblproducts.id) AS imageCount
FROM
    tblProducts
INNER JOIN
    tblProductCats ON tblProducts.categoryID = tblProductCats.ID

If the category ID for the product is 0 (tblProducts INNER JOIN tblProductCats ON tblProducts.categoryID = tblProductCats.ID) it will not return the product record, is there anyway to modify the query so it does return records with 0 as a value and shows the category name as 'Orphan'?

+4  A: 
SELECT ...
       ISNULL(tblProductCats.catName,'Orphan') AS  catName   ,
/*
Or possibly...
       CASE
              WHEN tblProducts.categoryID = 0
              THEN 'Orphan'
              ELSE tblProductCats.catName
       END AS catName
       */
       ...
FROM   tblProducts
       LEFT OUTER JOIN tblProductCats
       ON     tblProducts.categoryID = tblProductCats.ID
Martin Smith
Damnit, I was just about to post the same thing! lol, +1 anyway
Codesleuth
Thanks for the answer, if tblProducts.categoryID = 0 though then it doesn't return that record still. I think I need to use a different type of join?
Tom Gullen
My answer does use a different type of JOIN to your question. Are you saying left join doesn't work? If so do you have a WHERE clause you haven't shown us that is converting it to an inner join?
Martin Smith
Didn't notice that :) Perfect, thank you!
Tom Gullen