我有食物表(FOODS)和食物组表(FOOD_GROUP)。我已经建立了一个列表,根据用户输入的搜索词汇总每个组的可用食物数量:
SELECT FOOD_GROUP.FoodGroupID, FOOD_GROUP.FoodGroupName, Count(FOODS.FoodID) AS CntOfFoodID
FROM FOOD_GROUP LEFT JOIN FOODS ON FOOD_GROUP.FoodGroupID = FOODS.FoodGroupID
WHERE (((FOODS.FoodName) Like ("*" & [Forms]![FoodSearch]![search_term] & "*")))
GROUP BY FOOD_GROUP.FoodGroupID, FOOD_GROUP.FoodGroupName
ORDER BY FOOD_GROUP.FoodGroupName;
但现在变得棘手了。我想在列表顶部添加一个摘要行。这是一个近乎相似的例子:
我想我必须这样做:
SELECT '0000', 'Show all foods', Count(FOODS.FoodID) AS CntOfFoodID
FROM FOODS
WHERE (((FOODS.FoodName) Like ("*" & [Forms]![FoodSearch]![search_term] & "*")))
UNION
SELECT FOOD_GROUP.FoodGroupID, FOOD_GROUP.FoodGroupName, Count(FOODS.FoodID) AS CntOfFoodID
FROM FOOD_GROUP LEFT JOIN FOODS ON FOOD_GROUP.FoodGroupID = FOODS.FoodGroupID
WHERE (((FOODS.FoodName) Like ("*" & [Forms]![FoodSearch]![search_term] & "*")))
GROUP BY FOOD_GROUP.FoodGroupID, FOOD_GROUP.FoodGroupName
ORDER BY FOOD_GROUP.FoodGroupName;
但GROUP BY失败,如果我取出GROUP BY而不是FoodGroupID。
任何提示?
答案 0 :(得分:1)
我认为这应该有效:
SELECT '0000', 'Show all foods', Count(f.FoodID) AS CntOfFoodID
FROM FOODS as f
WHERE f.FoodName Like "*" & [Forms]![FoodSearch]![search_term] & "*"
UNION ALL
SELECT fg.FoodGroupID, fg.FoodGroupName, Count(f.FoodID) AS CntOfFoodID
FROM FOOD_GROUP fg LEFT JOIN
FOODS as f
ON fg.FoodGroupID = f.FoodGroupID
WHERE f.FoodName Like "*" & [Forms]![FoodSearch]![search_term] & "*"
GROUP BY fg.FoodGroupID, fg.FoodGroupName
ORDER BY 1;
变化是:
UNION
代替UNION ALL
。这样效率更高。ORDER BY
不引用列名(特别是仅在第二个子查询中的名称)。