1

Here are my conditions.

I have three tables with following columns

Recipe 
   - rID
   - pID
   - ingID
   - ingAmount

Product
   -pID
   -pName

Ingredient
   - ingID
   - ingName

for Recpe Table, Recipe.ingID, Recipe.pID is referenced from Product's Product.pID (Primary Key), While the same ingredient.ingID is also referenced from Product.ingID.

In general,

Recipe.pID = Product.pID
Recipe.ingID = Product.pID
Recipe.ingID = Ingredient.ingID

I want to retrieve following columns using just single query in ACCESS.

pID | pName | ingID | ingName | ingAmount |

I tried following:

SELECT Recipe.pID, Product.pName, Recipe.ingID, 
       Ingredient.ingName, Recipe.ingAmount 
  FROM Recipe, Product, Ingredient 
 WHERE Recipe.pID = 5 
       AND (
            Recipe.ingID = Ingredient.ingID 
            OR Recipe.ingID = Product.pID
           );

The problem is, (Recipe.ingID = Ingredient.ingID OR Recipe.ingID = Product.pID) part gets evaluated first hence multiple rows are queried.

If you got what I wanted to ask please help me.

6
  • Have you tried SELECT DISTINCT? Does that do what you want? Commented Jan 20, 2012 at 12:38
  • The condition should be Recipe.ingID = Ingredient.ingID AND Recipe.pID = Product.pID Commented Jan 20, 2012 at 12:53
  • @Florin: Nope! I want Recipe.ingID = Ingredient.ingID equals to true or Recipe.ingID = product.pID equals to true Commented Jan 20, 2012 at 16:19
  • @user995387 When you say "multiple rows are queried", what is the problem, are you getting duplicate records, if so on which field/fields? Commented Jan 20, 2012 at 17:50
  • Yeap duplicate records of ingID fields Commented Jan 21, 2012 at 7:07

1 Answer 1

1
SELECT Recipe.pID, Recipe.ingID, Recipe.ingAmount, 
       Ingredient.ingName AS element_name, 
       'Ingredient' AS element_type
  FROM Recipe INNER JOIN Ingredient
          ON Recipe.ingID = Ingredient.ingID 
 WHERE Recipe.pID = 5 
UNION
SELECT Recipe.pID, Recipe.ingID, Recipe.ingAmount, 
       Product.pName AS element_name, 
       'Product' AS element_type
  FROM Recipe INNER JOIN Product
          ON Recipe.pID = Product.pID
 WHERE Recipe.pID = 5
UNION
SELECT Recipe.pID, Recipe.ingID, Recipe.ingAmount, 
       Product.pName AS element_name, 
       'Product as Ingredient' AS element_type
  FROM Recipe INNER JOIN Product
          ON Recipe.ingID = Product.pID
 WHERE Recipe.pID = 5;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.