Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have 3 tables PostedRecipes, PostedRecipePictures, and RecipeRatings. PostedRecipes and PostedRecipePictures use RecipeID as the key. RecipeRatings uses RatingID as key but does have RecipeID as a column name.

Data from all 3 tables are combined to present a recipe (PostedRecipes) with a picture and rating.

PostedRecipes may have data without the other two having any data. Therefore, a recipe could be just a recipe, or a recipe with picture, or a recipe with picture and rating.

PostedRecipePictures nor RecipeRatings are required to input a PostedRecipe, however, if a RecipeID is entered on either PostedRecipePictures or RecipeRatings input must be made - there is no NULL on either.

I need to identify which PostedRecipes do not have a PostedRecipePictures, or a RecipeRatings, or both.

I have identified which PostedRecipes have PostedRecipePictures but cannot query which PostedRecipes do not have PostedRecipePictures or RecipeRatings.

Any guidance would be appreciated. I have tried the following queries.

What I have tried:

SELECT PostedRecipes.RecipeID, PostedRecipePictures.RecipeID AS Expr1
FROM PostedRecipes INNER JOIN
PostedRecipePictures ON PostedRecipes.RecipeID = PostedRecipePictures.RecipeID (gives the total # of common IDs but not where pics are missing)

SELECT PostedRecipes.RecipeID, PostedRecipePictures.RecipeID AS Expr1
FROM PostedRecipes INNER JOIN
PostedRecipePictures ON PostedRecipes.RecipeID = PostedRecipePictures.RecipeID AND PostedRecipes.RecipeID <> PostedRecipePictures.RecipeID (which gives no results)

SELECT PostedRecipes.RecipeID, PostedRecipePictures.RecipeID AS Expr1
FROM PostedRecipes INNER JOIN
PostedRecipePictures ON PostedRecipes.RecipeID = PostedRecipePictures.RecipeID AND PostedRecipes.RecipeID = PostedRecipePictures.RecipeID (which give the total of common ID but not what I need)
Posted
Updated 2-Oct-17 0:43am

1 solution

You need left join PostedRecipes to pictures or ratings in order to get the results you want. Inner join only selects the matching rows, while left join selects the matching rows or null if the row on the left doesn't have any match on the right.
SQL
SELECT PostedRecipes.RecipeID, PostedRecipePictures.RecipeID AS Expr1
FROM PostedRecipes 
LEFT JOIN PostedRecipePictures
    ON PostedRecipes.RecipeID = PostedRecipePictures.RecipeID
WHERE PostedRecipePictures.RecipeID IS NULL

Alternatively you can rewrite the query using NOT EXISTS
SQL
SELECT PostedRecipes.RecipeID
FROM PostedRecipes 
WHERE NOT EXISTS (
    SELECT * FROM PostedRecipePictures 
    WHERE PostedRecipePictures.RecipeID = PostedRecipes.RecipeID
)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900