Wednesday, March 21, 2012

need some help with my sql query

I'm still learning this stuff and I'm a bit confused. I have 3 tables: products, categories and subcategories. the products table has the foreign key for subcategories and the subcategories table has the foreign key for categories. I want to return a table that has the ProductID, SubCategoryID and CategoryID. I can't seem to fiqure out how to get the categoryID to the results table. I'm not sure if I'm supposed to use joins or subqueries to get the categoryID. All I have so far is this:


sql="SELECT Products.ProductID, Products.SubCategoryID FROM Products"

any help would be appreciated.I've come up with the following, i'm not sure if this is the correct way to do it, but it seems to work. I ran it through SQL Query Analyzer and it appears to give the results that i was expecting.


sql="SELECT Products.ProductID, Products.SubCategoryID, (SELECT CategoryID FROM SubCategories WHERE SubCategoryID = Products.SubCategoryID) as CategoryID
FROM Products";

If there is another/better/correct way to do this please let me know. Thanks.|||Another way to do it, which might be more efficient, is:


sql="SELECT Products.ProductID, Products.SubCategoryID, SubCategories.CategoryID FROM Products LEFT OUTER JOIN SubCategories ON Products.SubCategoryID = SubCategories.SubCategoryID";

Terri|||Very good, thanks. That is exactly what I was looking for.

No comments:

Post a Comment