在两个Mysql表中求和两列

时间:2011-06-24 09:31:22

标签: mysql

我一直在寻找这个,但没有雪茄。烟雾开始从我的耳朵里冒出来。请帮忙

如何将两个表中的两列相加并按用户ID分组?

有两张桌子。

Recipe Table
recipeid   userid   recipe_num_views

Meals Table
mealsid   userid    meal_num_views 

目标是按用户ID

对表和组中的num视图求和
so for example
Recipe Table
1    3     4
2    4     6

Meal Table
1    3     2
2    4     5


select sum(recipe views)+sum(meal views) 
WHERE recipe.userid=meals.userid GROUP BY userid

应该给出

userid=3 , sum=6
userid=4, sum=11

这给了一个更大的数字。

2 个答案:

答案 0 :(得分:13)

SELECT recipe.userid, sum(recipe_num_views+meal_num_views) 
FROM Recipe JOIN Meals ON recipe.userid=meals.userid
GROUP BY recipe.userid

编辑:

好的,从您的评论中我知道,当您有用户3 4个食谱& 3餐您将获得所有这些行的组合的总和=>的 sum(recipes)*3 + sum(meals)*4

请尝试此查询:

select r.userid, (sum_recipe + sum_meal) sum_all
FROM
(select userid, sum(recipe_num_views) sum_recipe
FROM Recipe
GROUP BY userid) r
JOIN (
select userid, sum(meal_num_views) sum_meal
FROM Meals
GROUP BY userid) m ON r.userid = m.userid

答案 1 :(得分:2)

如果您从2个表中进行选择,则需要加入它们。 否则MySQL将不知道如何链接这两个表。

select sum(recipe_num_views + meal_num_views) 
from recipe r
inner join meals m ON (r.user_id = m.user_id)
group by m.user_id

请参阅:
http://dev.mysql.com/doc/refman/5.5/en/join.html
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html