Sum Two Columns in Two Mysql Tables

后端 未结 2 2091
天命终不由人
天命终不由人 2020-12-07 01:16

I\'ve been searching everywhere for this but no cigar. Smoke is starting to come out of my ears. please help

How do you sum two columns in two tables and group by us

相关标签:
2条回答
  • 2020-12-07 01:18

    If you're selecting from 2 tables you need to join them. Otherwise MySQL will not know how to link up the two tables.

    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
    

    See:
    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

    0 讨论(0)
  • 2020-12-07 01:33
    SELECT recipe.userid, sum(recipe_num_views+meal_num_views) 
    FROM Recipe JOIN Meals ON recipe.userid=meals.userid
    GROUP BY recipe.userid
    

    EDIT:

    OK, from your comments, I understand that when you have for user 3: 4 recipes & 3 meals you will get the sum of the combination of all these rows => sum(recipes)*3 + sum(meals)*4

    Try this query instead:

    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
    
    0 讨论(0)
提交回复
热议问题