在加入其他表后获取表列的单独计数

时间:2010-07-26 19:02:19

标签: sql mysql

我在加入其他人后获得准确的列数时遇到问题。当一个列被连接时,我仍然希望得到它正在连接的表的DISTINCT计数。

餐厅有多餐,餐点有多个食物组,食物组有多种食物。

通过餐馆ID,我希望能够计算出餐厅有多少餐食,食物组和食材。

当我加入food_groups时,饭数也会增加(我明白这是自然行为,我只是不明白如何得到我需要的东西。)我尝试过DISTINCT以及我找到的其他东西,但似乎没有什么可以做的。我想将此保留为一个查询而不是将其拆分为多个查询。

SELECT 
    COUNT(meals.id) AS countMeals,
    COUNT(food_groups.id) AS countGroups,
    COUNT(ingrediants.id) AS countIngrediants
FROM 
    restaurants 
INNER JOIN 
    meals ON restaurants.id = meals.restaurant_id
INNER JOIN
    food_groups ON meals.id = food_groups.meal_id 
INNER JOIN
    ingrediants ON food_groups.id = ingrediants.food_group_id     
WHERE 
    restaurants.id='43'
GROUP BY
    restaurants.id

谢谢!

3 个答案:

答案 0 :(得分:3)

DISTINCT进入计数

SELECT 
    COUNT(DISTINCT meals.id) AS countMeals,
    COUNT(DISTINCT food_groups.id) AS countGroups,
    COUNT(DISTINCT ingrediants.id) AS countIngrediants
FROM 
    restaurants 
INNER JOIN 
    meals ON restaurants.id = meals.restaurant_id
INNER JOIN
    food_groups ON meals.id = food_groups.meal_id 
INNER JOIN
    ingrediants ON food_groups.id = ingrediants.food_group_id     
WHERE 
    restaurants.id='43'
GROUP BY
    restaurants.id

答案 1 :(得分:1)

我认为你将不得不做子查询。类似的东西:

SELECT 
    (SELECT COUNT(1) FROM meals m WHERE m.restaurant_id = r.id) AS countMeals,
    (SELECT COUNT(1) FROM food_groups fg WHERE fg.meal_id = m.id) AS countGroups,
    (SELECT COUNT(1) FROM ingrediants i WHERE i.food_group_id = fg.id) AS countGroups
FROM restaurants r

答案 2 :(得分:1)

你把DISTINCT和哪些列放在哪里?当使用COUNT()时,您需要在括号内进行区分,您需要在单个列上执行此操作,该列与您尝试计算的内容不同。例如:

SELECT
    COUNT(DISTINCT M.id) AS count_meals,
    COUNT(DISTINCT FG.id) AS count_food_groups,
    COUNT(DISTINCT I.id) AS count_ingredients
FROM
    Restaurants R
INNER JOIN Meals M ON M.restaurant_id = R.id
INNER JOIN Food_Groups FG ON FG.meal_id = M.id
INNER JOIN Ingredients I ON I.food_group_id = FG.id
WHERE 
    R.id='43'

由于您选择的是一家餐馆,因此您不需要GROUP BY。此外,除非这是非英语,我认为你拼错了成分。