这是我的条件。
我有三个包含以下列的表
Recipe
- rID
- pID
- ingID
- ingAmount
Product
-pID
-pName
Ingredient
- ingID
- ingName
对于Recpe Table,Recipe.ingID,Recipe.pID是从Product的Product.pID(主键)引用的,而相同的ingredient.ingID也是从Product.ingID引用的。
一般来说,
Recipe.pID = Product.pID
Recipe.ingID = Product.pID
Recipe.ingID = Ingredient.ingID
我想在ACCESS中使用单个查询来检索以下列。
pID | pName | ingID | ingName | ingAmount |
我试过以下:
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
);
问题是,首先评估(Recipe.ingID = Ingredient.ingID OR Recipe.ingID = Product.pID)
部分,因此查询多行。
如果你有我想问的问题,请帮助我。
答案 0 :(得分: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;