在SQL(访问)

时间:2017-07-01 10:24:36

标签: sql ms-access

我有食物表(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;

Food group | Count of foods matching the search term

但现在变得棘手了。我想在列表顶部添加一个摘要行。这是一个近乎相似的例子:

Ordered by Group name as above

我想我必须这样做:

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。

任何提示?

1 个答案:

答案 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不引用列名(特别是仅在第二个子查询中的名称)。
  • 表别名的使用只是简化了查询;它不会影响逻辑或性能。